Author Topic: How can I create a Singleton in Swift?  (Read 2777 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
How can I create a Singleton in Swift?
« on: January 29, 2015, 11:36:43 AM »
You can implement the Singleton design pattern in Swift like this:

Code: [Select]
private let singletonInstance = SingletonClass()
class SingletonClass {
    class var sharedInstance: SingletonClass {
        return singletonInstance
    }
}

You can then reference the Singleton instance like this:

Code: [Select]
SingletonClass.sharedInstance
This works, without the need to worry about dispatch_once (as in Objective-C) as stated on the Apple blog:

"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."

All the best!
Kevin
Author of Learn to Code in Swift: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11
« Last Edit: January 29, 2015, 11:40:42 AM by kjmcneish »