Skip to content

Instantly share code, notes, and snippets.

@rgcottrell
Last active May 24, 2023 21:57
Show Gist options
  • Save rgcottrell/fdc7dd7cf5bc3ed61010 to your computer and use it in GitHub Desktop.
Save rgcottrell/fdc7dd7cf5bc3ed61010 to your computer and use it in GitHub Desktop.
Thread safe shared instance "singletons" in Swift.
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static var token: dispatch_once_t = 0
static var instance: Singleton!
}
dispatch_once(&Static.token) {
Static.instance = Singleton()
}
return Static.instance
}
init() {
println("Init the Singleton!")
}
}
//
// UPDATE
//
// Static variables in a struct are lazily initialized, so there's no need for the dispatch once.
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static let instance: Singleton! = Singleton()
}
return Static.instance
}
init() {
println("Init the Singleton!")
}
}
// Alternatively, a global variable, which is also lazily initialized, could be used to store the shared instance.
// A class method could optionally be added to provide a more object-oriented access to the shared instance.
let SingletoneSharedInstance: Singleton = Singleton()
class Singleton {
class var sharedInstance: Singleton {
return SingletoneSharedInstance
}
init() {
println("Init the Singleton!")
}
}
@art-divin
Copy link

I think its worth mentioning one-liner singleton pattern like from here since this gist is topmost in google search

@ilandbt
Copy link

ilandbt commented Jun 13, 2017

Hi, what part of this makes it thread safe?

@rgkobashi
Copy link

@ilandbt Swift initialize global variables (line 40) in an atomic way when they are first accessed :)

@ktolstikhin
Copy link

In Swift 3.0, you can simplify things even further:

class Singleton {
    static let sharedInstance = Singleton()
    private init() { }
}

@tana90
Copy link

tana90 commented Feb 11, 2020

Hi, what part of this makes it thread safe?

True! :)

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