#16: Singletons in Swift 3

From Swift 3 you will not need to fiddle with dispatch_once anymore to write singletons, as explained here you will be able to build a singleton class leveraging the fact that global properties are guaranteed to be initialized atomically and that constants cannot be modified once they are set with a value.

Even in presence of multiple threads, our static and shared property will be initialized only by the first thread that tries to access the value and other threads will not be able to observe the value while is being set.


final class Singleton {

    public static let shared = Singleton()

    private init() { }

}

The singleton constructor is made private to prevent any attempt to manually generate instances of this class and with final nobody will be able to subclass it.

This short post is one of the Swift Bites, click the link for more!


This is the blog of Umberto Raimondi, you can reach me at me@this domain.

I'm also on Twitter and GitHub.

Subscribe via RSS or email.