Singleton Pattern in Swift

$ grep -i "singleton haters" > /dev/null
ObjectiveC’s singleton pattern in Swift (see StackOverflow for alternates):
import Foundation

class X {
  struct Static {
    static var token : dispatch_once_t = 0
    static var instance : X?

  class var instance: X {
    dispatch_once(&Static.token) {  Static.instance = X() }
    return Static.instance!

    assert(Static.instance == nil, "Singleton already initialized!")
The Singleton pattern uses dispatch_once and tracks the dispatch token as well as the instance as static variables (wrapped in a struct to work around compiler issues). An assert in init prevents subsequent instances from being created. import Foundation is required to use dispatch_once. The singleton instance is accessed as a class property:
//Output: C11lldb_expr_01X (has 0 children)
Attempts to create additional instances of X are rejected:
//Output: assertion failed: Singleton already initialized!: file <REPL>, line 19
  • A problem like this:

    var xInstance = X()
    var anotherIns = X()

    x.instance must be the first call for you scenario to work

  • slayer

    xcode beta 3
    assert(!Static.instance == true, “Singleton already initialized!”)