Fields
A field is a stored value attached to a struct. Each field has a name, a type, and a mutability declaration.
Declaring fields
struct Player {
let name: String // immutable after init
var hp: Int // mutable
var inventory: [String] // mutable
}
let fields are set once, in the initializer, and can't change after. var fields can be reassigned anytime — by methods marked mutating, or by external code holding the struct via var.
Defaults
The memberwise initializer always takes every field. To make a field optional at construction, write your own init and give its parameter a default value:
struct Config {
var port: Int
let strict: Bool
init(strict strict: Bool, port port: Int = 8080) {
self.port = port;
self.strict = strict;
}
}
let c = Config(strict: true); // port defaults to 8080
let d = Config(strict: false, port: 9000); // override
Defaulted parameters must come after the required ones. See Initializers for the full rules.
Field access
Read a field with dot syntax:
<!-- sample: continue -->let portInUse = c.port;
Write to a var field — provided you hold the struct via var:
var server = Config(strict: true);
server.port = 9001; // ok
let fields can't be written even from inside a mutating method. They're sealed at the type level.