It’s not easy to implement a simple singleton in fast

I created a new file ->swift file . called Globals.Swift then I did:

 class Globals { static let sharedInstance = Globals() init() { var max=100 } } 

In another class ( UIViewcontroller ) I would like to use it,

 Globals.sharedInstance //is going ok 

ok, but when I delve into .max , I get an error.

+5
source share
1 answer

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) // 100 singleton.max = 42 print(singleton.max) // 42 

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 .

+9
source

Source: https://habr.com/ru/post/1245087/


All Articles