Creating a Variable
Declare a new variable with var, followed by a name, type, and value:
var num: Int = 10
Variables can have their values changed:
num = 20 // num now equals 20
Unless they’re defined with let:
let num: Int = 10 // num cannot change
Property Observers
Property observers respond to changes to a property’s value.
var myProperty = 5 {
willSet {
print(“Will set to \(newValue). It was previously \(myProperty)”)
}
didSet {
print(“Did set to \(myProperty). It was previously \(oldValue)”)
} }
myProperty = 6
// prints: Will set to 6, It was previously 5
willSet is called before myProperty is set. The new value is available as newValue, and the old value is still available as myProperty.
didSet is called after myProperty is set. The old value is available as oldValue, and the new value is now available as myProperty .
Lazy Stored Properties
Lazy stored properties have values that are not calculated until first accessed. This is useful for memory saving when the variable’s calculation is computationally expensive.
lazy var lazyProperty: Int = {
print(“Initializing lazy property”)
return 42
}()
- Lazy stored properties must be declared with var.
- Lazy properties are particularly useful for optimizing performance by deferring the initialization of properties until they are actually needed
Computed Properties
Different from stored properties, computed properties are built with a getter and a setter, performing necessary code when accessed and set. Computed properties must define a type:
var radius = 0.0
var circumference: Double {
return 2 * Double.pi * radius
}
Type Properties
Type properties are properties on the type itself, not on the instance. They can be both stored or computed properties. Declare a type property with static:
struct Subject {
static var name = “Code with swift !”
}
print(Subject.name) // Prints “Code with swift !”
In a class, we can use the class keyword instead of static to make it overridable. However, we can only apply this on computed properties:
class Animal {
class var animal: String {
return “Animal”
}
}
class Dog: Animal {
override class var animal: String {
return “Dog”
}
}