Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are willset and didset considered closures in Swift?

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() }
}
like image 469
agy Avatar asked Jul 23 '15 06:07

agy


People also ask

What is didSet and willSet in Swift?

willSet is called just before the value is stored. didSet is called immediately after the new value is stored.

What is difference between willSet and didSet in Swift?

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.

What are closures in Swift?

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.

Is didSet called in init?

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.


1 Answers

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.)

like image 187
jtbandes Avatar answered Sep 25 '22 13:09

jtbandes