加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

“dispatch_once_t”在Swift中不可用:使用懒惰初始化的全局变量

发布时间:2020-12-14 05:36:33 所属栏目:百科 来源:网络整理
导读:参见英文答案 Whither dispatch_once in Swift 3?6 Using a dispatch_once singleton model in Swift25个 迁移到Swift 3时,dispatch_once_t有问题. 根据Apple’s migration guide: The free function dispatch_once is no longer available in Swift. In Sw
参见英文答案 > Whither dispatch_once in Swift 3?6
> Using a dispatch_once singleton model in Swift25个
迁移到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!
}

但是当我运行这个访问返回时,我得到以下错误Static.instance !:

fatal error: unexpectedly found nil while unwrapping an Optional value

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

即使Swift 2中有效,该代码过于冗长.在Swift 3中,Apple强制您通过关闭来使用延迟初始化:
class CarsConfigurator {
    static let sharedInstance: CarsConfigurator = { CarsConfigurator() }()
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读