Global var vs Shared Instance swift

What is the difference between a global variable and a shared instance in Swift? what is their scope? Can anyone please clarify their Swift based concept.

+3


source to share


2 answers


A global variable is a variable declared at the top level in a file. So if we have a class named Bar

, you can store the instance reference Bar

in a global variable like this:

var bar = Bar()

      

Then you should be able to access the instance from anywhere, for example:

bar
bar.foo()

      

A generic 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 (besides the fact that globals are simply discouraged) is that the singleton pattern restricts you from creating other instances Bar

. In the first example, you can simply create more global variables:

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

      

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

var baaar = Bar()

      

... results in the following:

'Bar' initializer not available due to 'private' security level

This is good because the point of a singleton is that there is one shared instance. Now the only way to access the instance Bar

is through Bar.shared

. It is important to remember to add private init()

to the class and not add any other initializers, or this will no longer apply.

If you need more information on this there is a great KrakenDev article here .

+5


source


Singleton (shared instance)

Make sure that only one instance of the singleton object is created and that it provides global access through a shared object instance that can be shared even through the application. Dispatch_once function that executes the block once and only once for the lifetime of an app

.



Global variable

Apple documentation says that global variables are variables that are defined outside of any function, method, closure, or type context

.

-2


source







All Articles