SoFunction
Updated on 2025-04-10

Analyze Swift singleton mode with examples

Three methods to implement singleton mode in Swift: global variables, internal variables, dispatch_once method

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  
    } 
  } 
}  

3. dispatch_once method

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

The above is the entire content of this article, I hope you like it.