Lazy initialization and deinit

五迷三道 提交于 2019-12-24 06:49:56

问题


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?


回答1:


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?.something
thing = nil // Prints "deinit" and "Hello"


来源:https://stackoverflow.com/questions/44259194/lazy-initialization-and-deinit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!