Created
October 19, 2017 15:38
-
-
Save devpeds/0a3874f04577c622fd803632ee4ee136 to your computer and use it in GitHub Desktop.
Thread-Safe Singleton Pattern in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment