Stored properties
As you may have guessed from the example in the introduction, you’re already familiar with many of the features of stored properties. To review, imagine you’re building an address book. The common unit you’ll need is a Contact:
struct Contact {
var fullName: String var emailAddress: String
}
You can use this structure over and over again, letting you build an array of contacts, each with a different value. The properties you want to store are an individual’s full name and email address.
These are the properties of the Contact structure. You provide a data type for each, but opt not to assign a default value, because you plan to assign the value upon initialization. After all, the values will be different for each instance of Contact.
Remember that Swift automatically creates an initializer for you based on the properties you defined in your structure:
var person = Contact(fullName: "Grace Murray",
emailAddress: "[email protected]")
You can access the individual properties using dot notation:
let name = person.fullName // Grace Murray
let email = person.emailAddress // [email protected]
You can assign values to properties as long as they’re defined as variables (and the instance is stored in a variable as well). When Grace married, she changed her last name:
person.fullName = "Grace Hopper"
let grace = person.fullName // Grace Hopper
If you’d prefer to make it so that a value can’t be changed, you can define a property as a constant instead using let:
struct Contact {
var fullName: String let emailAddress: String
}
// Error: cannot assign to a constant person.emailAddress = "[email protected]"
Once you’ve initialized an instance of this structure, you can’t change emailAddress.