You cannot just have var = xxx
in init. The variable must be declared at the top level of the class.
An example of using your singlet:
class Globals { static let sharedInstance = Globals() var max: Int private init() { self.max = 100 } } let singleton = Globals.sharedInstance print(singleton.max)
When you need to use singleton in another class, you just do it in another class:
let otherReferenceToTheSameSingleton = Globals.sharedInstance
Update after comments by Martin R and Caleb: I made the initializer closed. It prevents Globals()
initializing in other Swift files, forcing this class to behave as a single, only having the ability to use Globals.sharedInstance
.
source share