Swift 3 - Singleton

女生的网名这么多〃 提交于 2019-12-12 03:48:29

问题


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 

calling it

 aManager = MyManager.sharedInstance

results in

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

回答1:


_ = 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.




回答2:


For me this is the best way, make init private.

// MARK: - Singleton

final class Singleton {

    // Can't init is singleton
    private init() { }

    // MARK: Shared Instance

    static let shared = Singleton()

    // MARK: Local Variable

    var emptyStringArray : [String] = []

}


来源:https://stackoverflow.com/questions/40754852/swift-3-singleton

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!