2

I have a class

class SomeClass {
    lazy var property1: Int = {
        return 1
    }()

    lazy var property2: Int = {
       return self.property1
    }()

    deinit {
        print("SomeClass will be destroyed")
    }
}

If I have the following in playground:

var a: SomeClass? = SomeClass()
print(a?.property1)
print(a?.property2)
a =  nil

then the variable a will be deinitialized as SomeClass will be destroyed message will appear. However if I comment out the accesses to the properties like:

var a: SomeClass? = SomeClass()
//print(a?.property1)
//print(a?.property2)
a =  nil

I still got the message SomeClass will be destroyed. I would expect that there is a reference cycle as the closure of property2 is never called and it references self through self.property1.

Is there something special with lazy variables or just my assumption is wrong that property2 hold a reference to self?

1 Answer 1

3

The reason that there isn't is a reference cycle is because the closure isn't stored on a. If a stored the closure and the closure contained self then there would be a reference cycle.

For lazy properties, everything after the = isn't called until the first time you access property2. When you do, the closure is created, called, freed from memory, and then the value is returned to you. This is why you can get rid of the self. in the closure since it will never capture self.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer, it makes sense! Do you have a reference however on the first part, that the closure isn't stored on a? Or where is it stored?
Since the closure is immediately called, it isn't stored anywhere. It's no different than just calling a function for getting the initial value. ie lazy var property2: Int = someValue()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.