Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having hard time implement a simple singleton in swift

Tags:

swift

I have created a new file ->swift file . called Globals.Swift Then in there I have done :

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

is good, but when i go deep to .max i get the error.

like image 497
Curnelious Avatar asked Mar 15 '16 12:03

Curnelious


1 Answers

You can't just have var = xxx in an init. The variable has to be declared at the class top level.

Example of using your singleton:

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 the singleton in another class, you just do this in the other class:

let otherReferenceToTheSameSingleton = Globals.sharedInstance

Update following Martin R and Caleb's comments: I've made the initializer private. It prevents, in other Swift files, the initialization of Globals(), enforcing this class to behave as a singleton by only being able to use Globals.sharedInstance.

like image 146
Eric Aya Avatar answered Oct 03 '22 06:10

Eric Aya