Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global var vs Shared Instance swift

What is the difference between global variable and shared instance in Swift? what are their respective field of use? Could anyone clarify their concept based upon Swift.

like image 645
Parion Avatar asked Jul 06 '17 04:07

Parion


1 Answers

A global variable is a variable that is declared at the top level in a file. So if we had a class called Bar, you could store a reference to an instance of Bar in a global variable like this:

var bar = Bar()

You would then be able to access the instance from anywhere, like this:

bar
bar.foo()

A shared instance, or singleton, looks like this:

class Bar {
    static var shared = Bar()
    private init() {}
    func foo() {}
}

Then you can access the shared instance, still from anywhere in the module, like this:

Bar.shared
Bar.shared.foo()

However, one of the most important differences between the two (apart from the fact that global variables are just generally discouraged) is that the singleton pattern restricts you from creating other instances of Bar. In the first example, you could just create more global variables:

var bar2 = Bar()
var bar3 = Bar()

However, using a singleton (shared instance), the initialiser is private, so trying to do this...

var baaar = Bar()

...results in this:

'Bar' initializer is inaccessible due to 'private' protection level

That's a good thing, because the point of a singleton is that there is a single shared instance. Now the only way you can access an instance of Bar is through Bar.shared. It's important to remember to add the private init() in the class, and not add any other initialisers, though, or that won't any longer be enforced.

If you want more information about this, there's a great article by KrakenDev here.

like image 117
Søren Mortensen Avatar answered Oct 06 '22 16:10

Søren Mortensen