What is the difference between willSet - didSet, and get - set, when working with this inside a property?
From my
get set:
getsetare Computed Properties Which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly
Additionally you can define Read-Only Computed Properties. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value
Example get only property-
var number: Double {
return .pi*2
}
willSet didSet:
willSetdidSetare Property ObserversProperty observers observe and respond to changes in a property’s value. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.
Example -
var score: Int = 0 {
willSet(newScore) {
print("willSet score to \(newScore)")
}
didSet {
print("didSet score to \(oldValue) new score is: \(score)")
}
}
score = 10
//Output
//willSet score to 10
//didSet score to 0 new score is: 10
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html