在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
}()
$ b b
问题是,在某些时候,我需要重置这个 aClient
变量,以便当 ClinetSession .shared()
更改。但是如果我将类设置为可选 Clinet?
,当我尝试将其设置为 nil
。如果我只是在代码中使用 aClient = Clinet(ClinetSession.shared())
重置它,它将最终以 EXEC_BAD_ACCESS
。
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
.
有没有办法可以使用 lazy
并允许重置本身?
Is there a way that can use lazy
and being allowed to reset itself?
谢谢!
推荐答案
lazy是一次性初始化。您要采用的模型可能只是一个按需初始化模型:
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 {
get {
if(_aClient == nil) {
_aClient = Client(ClientSession.shared())
}
return _aClient!
}
}
var _aClient:Client?
现在每当 _aClient
c> nil ,它将被初始化并返回。可以通过设置 _aClient = nil
Now whenever _aClient
is nil
, it will be initialized and returned. It can be reinitialized by setting _aClient = nil
这篇关于在Swift中重新初始化一个延迟初始化的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!