TL ; DR:
A getter reads a private field. A setter changes it, but only to a value the class allows.
In Swift, other code reads and sets a property directly. To check each new value, give the property a didSet block. Swift runs it right after every change.
class Dog {
var age: Int {
didSet {
if age < 0 {
age = oldValue
}
}
}
init(_ age: Int) {
self.age = age
}
}
Full lesson:
In the Access Modifiers lesson, the property was private and getName() read it. In Swift, a property can guard itself instead.
The setter part: didSet
Write the didSet block in braces after the property. Now rex.age = 4 stores 4 and then runs the block.
Inside didSet, age already holds the new value. The old one is in oldValue.
The rule
A dog's age can't be negative. So when age is below 0, the block sets it back to oldValue. Setting a property inside its own didSet doesn't run the block again.
The getter part
Reading rex.age needs no code. A stored property simply returns its value.
The other way: computed properties
A computed property has get and set blocks. It stores nothing itself. It reads and writes a private stored property instead.
private var storedAge = 0
var age: Int {
get { return storedAge }
set {
if newValue >= 0 {
storedAge = newValue
}
}
}
Inside set, the new value is called newValue. Use a computed property when reading must compute something. To check a new value, didSet is shorter.
Your task
Add a property age of type Int to the Dog class. Give it a didSet block. When the new age is negative, the block puts back the old one.
The init sets the first age. The code in mainFunction creates rex, then reads and sets rex.age.
Expected output:
Rex is 3
Rex is still 3
Rex is 4Free plan: 30 tutor messages. Premium is unlimited.
