Skip to content

Instantly share code, notes, and snippets.

@oliverbarreto
Created November 1, 2015 18:09
Show Gist options
  • Save oliverbarreto/3f2d89a3dd3e9aca8f4b to your computer and use it in GitHub Desktop.
Save oliverbarreto/3f2d89a3dd3e9aca8f4b to your computer and use it in GitHub Desktop.
Swift Singleton Pattern
// See this GitHub project for unit tests: https://github.com/hpique/SwiftSingleton
// 1. Class constant
// This approach supports lazy initialization because Swift lazily initializes class constants (and variables), and is thread safe by the definition of let.
// Class constants were introduced in Swift 1.2. If you need to support an earlier version of Swift, use the nested struct approach below or a global constant.
class Singleton {
static let sharedInstance = Singleton()
}
// 2. Nested struct
// Here we are using the static constant of a nested struct as a class constant. This is a workaround for the lack of static class constants in Swift 1.1 and earlier, and still works as a workaround for the lack of static constants and variables in functions.
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static let instance: Singleton = Singleton()
}
return Static.instance
}
}
// dispatch_once
// The traditional Objective-C approach ported to Swift. I'm fairly certain there's no advantage over the nested struct approach but I'm putting it here anyway as I find the differences in syntax interesting.
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