Properties Flashcards
Type Properties:
If you want to have create a struct named LevelTracker with a single constant type property maxLevel, what must you include in the struct?
Static static let maxLevel = 1
Type Properties:
What are type properties?
struct Point {
var x: Int = 0
var y: Int = 0
}
struct Map { static var origin = Point(x: 1, y: 1) } Map.origin = Point(x: 2, y: 2)
So basically there will only be one copy of this property, no matter how many instances of that type you create.
Computed Properties:
What is the difference between stored and computed properties?
Stored properties store constant and variable values as part of an instance.
- let length: Int
Computed properties calculate a value instead of storing it
var area: Int {
return length * width
}
Computed Properties:
For the area property, this is a read only property. If you wanted to make it a read and right property, what would you have to use?
Get and set
If we don’t specify a constant to bind the value in a computed property’s setter, it is automatically bound to a variable named
newValue
Type properties are associated with the?
Type itself
A computed property that does not specify a getter or setter is by default a
Read only computed property
Lazy Stored Properties:
What is a lazy stored property?
A property whose initial value is not calculated until the first time we use it.
Basically, it makes sure no computational power is wasted until it is used.
Lazy Stored Properties:
Why does a lazy stored property have to be stored as a var?
Because it might change when you eventually decide to use it.
Lazy Stored Properties:
What is the value of a lazy stored property before it is defined?
It does not have a value
Property Observers:
What do property observers do?
Property observers allow us to observe and respond to changes in property values.
Property Observers:
What are 2 examples of property observers?
willset and didset are property observers. - they allow us to observe changes in a properties value
willSet {
print(“Old value: (value)”)
}
didSet { view.alpha = CGFloat(value) print("New value: \(value)") }
Property Observers:
When are willSet and didSet called?
didSet is executed after the value has been assigned.
willSet is called before the underlying value has been changed.
What’s the purpose of us creating type properties?
There will only be one copy of this property, no matter how many instances of that type you create.
So it’s going to always have one value no matter what.