Swift 3 - 单例 [英] Swift 3 - Singleton

查看:29
本文介绍了Swift 3 - 单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class MyManager {

private static var __once: () = {
    Static.instance = MyManager()
}()

class var sharedInstance: MyManager {
    struct Static {
        static var onceToken: Int = 0
        static var instance: MyManager? = nil
    }
    _ = MyManager.__once
    return Static.instance!
}

fileprivate init() {
    print("MyManager init");

}
....... etc 

调用它

 aManager = MyManager.sharedInstance

结果

 MyManager init fatal error: unexpectedly found nil while unwrapping an Optional value

推荐答案

_ = MyManager.__once 没有调用您的 __once 函数,而是将其分配给空.你忘记了 ():

_ = MyManager.__once isn't calling your __once function, it's assigning it to nothing. You forgot the ():

 MyManager.__once()

这就是要求 _ = 的全部目的,让您意识到您正在处理的是函数本身,而不是函数调用.

That's the whole purpose of requiring _ =, to make you realize you're dealing with the function itself, not a function call.

无论如何,这是一个不必要的复杂和混乱的单例实现.您只需要:

Regardless, this is an unnecessarily convoluted and messy implmentation of a singleton. All you need is:

class MyManager {
    static let instance = MyManager()
}

它是懒惰的、线程安全的、理智的.

It's lazy, thread-safe, and sane.

这篇关于Swift 3 - 单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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