Chapter 11: Properties
大綱
Stored properties
struct Contact {
// provide a data type for each one but opt not to assign a default value, because you plan to assign the value upon initialization.
var fullName: String
let emailAddress: String
var relationship = "Friend"
}
// Swift automatically creates an initializer for you based on the properties you defined in your structure
var person = Contact(fullName: "Grace Murray",
emailAddress: "grace@navy.mil",
relationship: "Friend")
// access the individual properties using dot notation
let name = person.fullName // Grace Murray
let email = person.emailAddress // grace@navy.mil
// assign values to properties as long as they’re defined as variables, and the parent instance is stored in a variable
person.fullName = "Grace Hopper"
let grace = person.fullName // Grace Hopper
// If you’d like to prevent a value from changing, you can define a property as a constant using "let"
person.emailAddress = "grace@gmail.com" // Error!Default values
Computed properties
Getter and setter
Type properties
Property observers
Limiting a variable
Lazy properties
Key points
Last updated