How to Create Singleton Object in swift

I am learning about Singleton pattern in swift and efficient way to create a Singleton class and found out the best way to create as below.

class SingletonClass{
    static let sharedInstance = SingletonClass()
}

Since i have use the let statement it is read only property and has to be thread safe so there is no need of dispatch_once() as of Objective C.And static is used to make the sharedInstance variable as a class variable i guess.

But how does this guarantee there is only one instance created throughout the application?is there a small thing i am missing?


What guarantees it is only created once is the keyword static . you can reference this article: https://thatthinginswift.com/singletons/

Hope that helps.

The static keyword denotes that a member variable, or method, can be accessed without requiring an instantiation of the class to which it belongs. In simple terms, it means that you can call a method, even if you've never created the object to which it belongs


如果你想阻止你的类的实例化(有效地限制使用只有单例),那么你将初始化器标记为private

 class SingletonClass{
        static let shared = SingletonClass()
    private init()
        {
            // initializer code here
        }
    }

创建私有的init,例如:

final class Singleton {

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

    //MARK: Shared Instance

    static let sharedInstance: Singleton = Singleton()

    //MARK: Local Variable

    var emptyStringArray : [String] = []

}
链接地址: http://www.djcxy.com/p/78854.html

上一篇: 迅速派遣一次不需要

下一篇: 如何在swift中创建单例对象