'dispatch_once_t'在Swift中不可用:请使用延迟初始化的全局变量 [英] 'dispatch_once_t' is unavailable in Swift: Use lazily initialized globals instead

查看:898
本文介绍了'dispatch_once_t'在Swift中不可用:请使用延迟初始化的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在迁移到Swift 3时,我遇到了dispatch_once_t的问题.

I am having trouble with dispatch_once_t when migrating to Swift 3.

根据 Apple的迁移指南:

免费功能dispatch_once在Swift中不再可用.在 Swift,您可以使用延迟初始化的全局变量或静态属性,以及 获得与dispatch_once相同的线程安全性和一次调用保证 假如.示例:

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.

所以我想迁移此代码.所以是在迁移之前:

So I wanted to migrate this code. So it was before migration:

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的准则(手动迁移),代码如下:

After the migration, following the Apple's guidelines (manual migration), the code looks like this:

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

    _ = Static.token

    return Static.instance!
}

但是运行此程序时,访问return Static.instance!时出现以下错误:

But when I run this I get the following error when accessing return Static.instance!:

致命错误:解开可选值时意外发现nil

fatal error: unexpectedly found nil while unwrapping an Optional value

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

I see from this error that the instance member is nil, but why is it? Is it something wrong with my migration?

推荐答案

即使在Swift 2中有效,该代码也过于冗长.在Swift 3中,Apple强迫您通过闭包使用惰性初始化:

That code was overly verbose even though it was valid in Swift 2. In Swift 3, Apple forces you to use lazy initialization through closure:

class CarsConfigurator {
    static let sharedInstance: CarsConfigurator = { CarsConfigurator() }()
}

这篇关于'dispatch_once_t'在Swift中不可用:请使用延迟初始化的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆