Search code examples
swift

Re-initialize a lazy initialized variable in Swift


I have a variable that initialized as:

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

The problem is, at some point, I need to reset this aClient variable so it can initialize again when the ClinetSession.shared() changed. But if I set the class to optional Clinet?, LLVM will give me an error when I try to set it to nil. If I just reset it somewhere in the code using aClient = Clinet(ClinetSession.shared()), it will end up with EXEC_BAD_ACCESS.

Is there a way that can use lazy and being allowed to reset itself?


Solution

  • lazy is explicitly for one-time only initialization. The model you want to adopt is probably just an initialize-on-demand model:

    var aClient:Client {
        if(_aClient == nil) {
            _aClient = Client(ClientSession.shared())
        }
        return _aClient!
    }
    
    var _aClient:Client?
    

    Now whenever _aClient is nil, it will be initialized and returned. It can be reinitialized by setting _aClient = nil