Singleton with Swift 3.0

前端 未结 6 1711
灰色年华
灰色年华 2021-01-15 04:33

I had this implementation with Swift 2.0 and the Xcode suggestion is not only baffling but causes compilation error as well. it\'s a library where users are passing callfunc

6条回答
  •  半阙折子戏
    2021-01-15 05:02

    Create a singleTon class as follows :

         class mySingleTon{
            
            //1. gives you SingleTon object which is created only once.
            static let sharedInstance = mySingleTon() 
            
            //2. make init private so it  prevents others from using the default '()' initializer for this class.    
            private init(){
            print("i am born")
            }
        
            func foo()
            {
            print("hello")
            }
        }
    

    Example usage :

    class A{
    func bar()
    {
      mySingleTon.sharedInstance.foo()
    
    //3. Uncomment to get error : initializer is inaccessible due to 'private' protection level.
    // let newSharedInstance = mySingleTon()
    }
    
    let a = A()
    let b = A()
    a.bar()
    b.bar()
    

    Output :

    i am born

    hello

    hello

    As you noticed Initializer is only called once. As per apple docs :

    “The lazy initializer for a global variable (also for static members of structs and enums) is run the first time that global is accessed, and is launched as dispatch_once to make sure that the initialization is atomic. This enables a cool way to use dispatch_once in your code: just declare a global variable with an initializer and mark it private.”

    Explaining Comments :

    1. Static member of class implicitly calls "dispatch_once" hence it is thread safe.

    2. Making init private prevents initialisation again.

    3. Test code line to prove initialisation is private.

提交回复
热议问题