Lazy initialization and deinit
Asked Answered
S

1

2

I would to know if it's possible, in my view controller, use a lazy property and in deinit method call a method of my lazy property only if it was initialized. Below some code:

fileprivate lazy var session: MySession = {
    let session: MySession = MySession()
    session.delegate = self
    return session
}()

deinit {
    session.delete()
}

In this way, when session.delete() in the deinit method is called and session hasn't been used (so is still nil), it's initialized and then delete is called. I don't want this. I'd like to call delete only if session had been previously initialized.

Is there a way to achieve this? Have I to let go the lazy initialization idea?

Sclerenchyma answered 30/5, 2017 at 10:3 Comment(0)
O
7

You can use a private variable to track if the session has been created. This example does what you want, I think (code from a playground):

class Thing {
    private var hasMadeSession: Bool = false
    lazy fileprivate var session: Int = {
        self.hasMadeSession = true
        return 1
    }()
    
    deinit {
        print(#function)
        if self.hasMadeSession {
            print("Hello")
        }
    }
}

var thing: Thing? = Thing()
thing = nil // Prints "deinit"
thing = Thing()
thing?.session
thing = nil // Prints "deinit" and "Hello"
Osis answered 30/5, 2017 at 10:22 Comment(1)
Thanks! I could've figured that out for myself :-)Sclerenchyma

© 2022 - 2024 — McMap. All rights reserved.