I understand the purpose of willset
and didset
my I am not sure if they are considered closures.
If they were closures, shouldn't the following code produce a strong reference cycle?
var myProperty : Int = 0 {
didSet { self.callMyMethod() }
}
willSet is called just before the value is stored. didSet is called immediately after the new value is stored.
willSet is called before the data is actually changed and it has a default constant newValue which shows the value that is going to be set. didSet is called right after the data is stored and it has a default constant oldValue which shows the previous value that is overwritten.
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
willSet and didSet observers are not called when a property is first initialized. They are only called when the property's value is set outside of an initialization context.
No, they are not closures. You can think of it like a special type of function which is not directly accessible; it will only be called when the property changes. (The function is named myapp.MyStruct.myProperty.didset
; you can see this in the debugger.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With