Browse Questions
- willSet runs just before a new value is stored and didSet runs immediately after, letting you react to every change to a property.
- The three modes differ in where the authentication token lives and whether the output grows: Seal appends the token to the ciphertext, Token Protect returns the token separately so the ciphertext…
- These four declarations differ in two dimensions: whether the array itself is optional, and whether the elements inside are optional.
- Use .onTapGesture for standard taps, and .onSimultaneousGesture when you need two gestures to fire together without one cancelling the other.
Answer:
willSet runs just before a new value is stored and didSet runs immediately after, letting you react to every change to a property.
willSetreceives the incoming value asnewValue(renamable:willSet(newTotal)).didSetreceives the previous value asoldValue(renamable:didSet(previous)).
Code Example:
class StepCounter {
var totalSteps: Int = 0 {
willSet {
print("About to set totalSteps to \(newValue)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
let counter = StepCounter()
counter.totalSteps = 200
// About to set totalSteps to 200
// Added 200 steps
counter.totalSteps = 360
// About to set totalSteps to 360
// Added 160 steps
Common iOS uses:
- Refresh UI when a model changes (
var items: [Item] = [] { didSet { tableView.reloadData() } }) - Validate or clamp a value
- Persist a setting to
UserDefaultswhenever it changes
Key Points:
- Observers are called on every set, even when the new value equals the current value.
- Observers only work on stored properties you declare, or on inherited properties via
override.