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!
  }

  init(){
    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:

println(X.instance)
//Output: C11lldb_expr_01X (has 0 children)

Attempts to create additional instances of X are rejected:

X()
//Output: assertion failed: Singleton already initialized!: file <REPL>, line 19

2 thoughts on “Singleton Pattern in Swift

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s