gpt4 book ai didi

swift - 'dispatch_once_t' 在 Swift : Use lazily initialized globals instead 中不可用

转载 作者:IT王子 更新时间:2023-10-29 05:09:27 25 4
gpt4 key购买 nike

<分区>

我在迁移到 Swift 3 时遇到 dispatch_once_t 问题。

根据 Apple's migration guide :

The free function dispatch_once is no longer available in Swift. In Swift, you can use lazily initialized globals or static properties and get the same thread-safety and called-once guarantees as dispatch_once provided. Example:

let myGlobal = { … global contains initialization in a call to a closure … }()

_ = myGlobal // using myGlobal will invoke the initialization code only the first time it is used.

所以我想迁移这段代码。所以在迁移之前:

class var sharedInstance: CarsConfigurator
{
struct Static {
static var instance: CarsConfigurator?
static var token: dispatch_once_t = 0
}

dispatch_once(&Static.token) {
Static.instance = CarsConfigurator()
}

return Static.instance!
}

迁移后,按照 Apple 的指南(手动迁移),代码如下所示:

class var sharedInstance: CarsConfigurator
{
struct Static {
static var instance: CarsConfigurator?
static var token = {0}()
}

_ = Static.token

return Static.instance!
}

但是当我运行它时,在访问 return Static.instance! 时出现以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

我从这个错误中看到 instance 成员是 nil,但这是为什么呢?我的迁移有问题吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com