Skip to content

Instantly share code, notes, and snippets.

@devpeds
Created October 19, 2017 15:38
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devpeds/b8ea171e8ac9e1e2856f6ad12ba7cdb5 to your computer and use it in GitHub Desktop.
Save devpeds/b8ea171e8ac9e1e2856f6ad12ba7cdb5 to your computer and use it in GitHub Desktop.
Thread-Safe Singleton Pattern in Swift
/* 1. Class Constant : Lazy initialization is supported. Officially recommanded way */
class Singleton {
static let shared = Singleton()
private init() { } // prevent creating another instances.
}
/* 2. Nested Struct : Workaround for the lack of static class constants in Swift 1.1 and earlier. still useful
in functions, where static constants and varialbles cannot be used. */
class Singleton {
class var shared: Singleton {
struct Static {
static let instance: Singleton = Singleton()
}
return Static.instance
}
}
/* 3. dispatch_once : Traditional Objective-C style approach. */
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: Singleton? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = Singleton()
}
return Static.instance!
}
}
Copy link

ghost commented Aug 10, 2018

Is the recommended implementation really thread-safe?

@strooooke
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment