October 2017
Intermediate to advanced
210 pages
5h 32m
English
Let's look at how we implement the singleton pattern with Swift. The following code example shows how to create a singleton class:
class MySingleton {
static let sharedInstance = MySingleton()
var number = 0
private init() {}
}
Within the MySingleton class, we create a static constant named sharedInstance that contains an instance of the MySingleton class. A static constant like this can be called without having to instantiate the class. Since we declared the sharedInstance constant static, only one instance will exist throughout the lifecycle of the application, thereby creating the singleton pattern. We also created the private initiator that will restrict external code from creating another instance ...
Read now
Unlock full access