While using lazy initialisers, is there a chance of having retain cycles?
In a blog post and many other places [unowned self]
is seen
class Person { var name: String lazy var personalizedGreeting: String = { [unowned self] in return "Hello, \(self.name)!" }() init(name: String) { self.name = name } }
I tried this
class Person { var name: String lazy var personalizedGreeting: String = { //[unowned self] in return "Hello, \(self.name)!" }() init(name: String) { print("person init") self.name = name } deinit { print("person deinit") } }
Used it like this
//... let person = Person(name: "name") print(person.personalizedGreeting) //..
And found that "person deinit" was logged.
So it seems there are no retain cycles. As per my knowledge when a block captures self and when this block is strongly retained by self, there is a retain cycle. This case seems similar to a retain cycle but actually it is not.
lazy initialisation is a delegation of object creation when the first time that object will be called. The reference will be created but the object will not be created. The object will only be created when the first time that object will be accessed and every next time the same reference will be used.
Swift has a mechanism built right into the language that enables just-in-time calculation of expensive work, and it is called a lazy variable. These variables are created using a function you specify only when that variable is first requested.
A lazy stored property is a property whose initial value isn't calculated until the first time it's used. You indicate a lazy stored property by writing the lazy modifier before its declaration.
Lazy initialization of an object means that its creation is deferred until it is first used.
I tried this [...]
lazy var personalizedGreeting: String = { return self.name }()
it seems there are no retain cycles
Correct.
The reason is that the immediately applied closure {}()
is considered @noescape
. It does not retain the captured self
.
For reference: Joe Groff's tweet.
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