Browse Questions
- Codable is a type alias for Encodable & Decodable.
- You can add observers to stored properties you define, and to inherited stored or computed properties by overriding them in a subclass.
- Delegate protocols must inherit from AnyObject to restrict protocol conformance to classes, allowing delegate properties to be marked with the weak keyword.
- Subscribe to keyboard notifications to adjust your layout when the keyboard appears or hides, so it doesn't cover your input fields.
Answer: You can add observers to stored properties you define, and to inherited stored or computed properties by overriding them in a subclass.
| Property kind | Can add observers? |
|---|---|
Stored var you define | ✅ Yes |
Inherited stored property (via override) | ✅ Yes |
Inherited computed property (via override) | ✅ Yes |
| Computed property you define | ❌ No — put the logic in its set |
let constant | ❌ No — it never changes |
Code Example:
class Vehicle {
var currentSpeed = 0.0
var description: String { "traveling at \(currentSpeed) mph" }
}
class Car: Vehicle {
var gear = 1
// Observing an inherited stored property
override var currentSpeed: Double {
didSet {
gear = Int(currentSpeed / 10) + 1
}
}
}
let car = Car()
car.currentSpeed = 35
print(car.gear) // 4
Key Points:
- An overriding property observer cannot also provide its own setter — choose one or the other.
- You cannot add observers to an inherited read-only computed property, since it is never set.
- The superclass's own observers still run; the subclass's observers run around them.