#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.
Did you like this article? Let me know on Twitter or subscribe for updates!