Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy initialisation and retain cycle

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.

like image 712
BangOperator Avatar asked Jul 01 '16 09:07

BangOperator


People also ask

What is lazy initialization in Swift?

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.

Why we use lazy VAR in Swift?

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.

What is a lazy property in Swift?

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.

Which of the following is true about the lazy initialisation of objects?

Lazy initialization of an object means that its creation is deferred until it is first used.


1 Answers

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.

like image 197
Nikolai Ruhe Avatar answered Oct 05 '22 02:10

Nikolai Ruhe