Re-initialize a lazy initialized variable in Swift

前端 未结 7 836
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 11:08

I have a variable that initialized as:

lazy var aClient:Clinet = {
    var _aClient = Clinet(ClinetSession.shared())
    _aClient.delegate = self
    return          


        
7条回答
  •  青春惊慌失措
    2020-12-04 11:37

    There are some good answers here.
    Resetting a lazy var is indeed, desirable in a lot of cases.

    I think, you can also define a closure to create client and reset lazy var with this closure. Something like this:

    class ClientSession {
        class func shared() -> ClientSession {
            return ClientSession()
        }
    }
    
    class Client {
        let session:ClientSession
        init(_ session:ClientSession) {
            self.session = session
        }
    }
    
    class Test {
        private let createClient = {()->(Client) in
            var _aClient = Client(ClientSession.shared())
            print("creating client")
            return _aClient
        }
    
        lazy var aClient:Client = createClient()
        func resetClient() {
            self.aClient = createClient()
        }
    }
    
    let test = Test()
    test.aClient // creating client
    test.aClient
    
    // reset client
    test.resetClient() // creating client
    test.aClient
    

提交回复
热议问题