Create a singleton in Swift

Objective-C uses dispatch_once_t in GCD to ensure that the code inside is only called once, thereby ensuring the thread safety of singletons.

However, in Swift, because the original Dispatch once method is abandoned, once can not be used to create a singleton.

We can use struct to store type variables and use let to ensure thread safety.

(1) Scheme 1

class Manager {
    class var sharedManager: Manager {
        struct Static {
            static let sharedInstance: Manager = Manager()
        }
        return Static.sharedInstance
    }
}

(2) Scheme 2

class Manager {
    class var sharedManager: Manager {
        return sharedInstance
    }
}

private let sharedInstance = Manager()

(3) Scheme 3

class Manager {
    static let sharedInstance = Manager()
}

Guess you like

Origin blog.csdn.net/watson2017/article/details/132578891