Analyze the Swift singleton pattern by example

  • 2020-05-09 19:23:12
  • OfStack

There are three ways that Swift implements the singleton pattern: global, internal, and dispatch_once

1. Global variables


private let _singleton = Singleton() 
class Singleton: NSObject { 
  class var sharedInstance: Singleton { 
    get { 
      return _singleton 
    } 
  } 
} 

2. Internal variables


class Singleton { 
  class var sharedInstance: Singleton { 
    get { 
      struct SingletonStruct { 
        static let singleton: Singleton = Singleton() 
      } 
       return SingletonStruct.singleton 
    } 
  } 
}  

3. dispatch_once way


class Singleton { 
  class var sharedInstance: Singleton { 
    get { 
      struct SingletonStruct { 
        static var onceToken:dispatch_once_t = 0 
        static var singleton: Singleton? = nil 
      } 
      dispatch_once(&SingletonStruct.onceToken, { () -> Void in 
        SingletonStruct.singleton = Singleton() 
      }) 
      return SingletonStruct.singleton! 
    } 
  } 
} 

That's all for this article, I hope you enjoy it.


Related articles: