swiftlazy-initializationdeinit

Lazy initialization and deinit


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?


Solution

  • 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"