Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - init in singleton class?

I have a singleton class MyClass for management work with third party sdk. Inside singleton I have init method.

My question is : does init method called every time I call something from singleton like MyClass.shared.mymethod() or in order to call init I have to call var instance = MyClass() ?

like image 944
Alexey K Avatar asked Nov 05 '16 12:11

Alexey K


People also ask

Can we de init a singleton object?

If you have a regular object that you can't deinitialize it's a memory problem. Singletons are no different, except that you have to write a function to do it. Singletons have to be completely self managed. This means from init to deinit.

What is singleton class Swift?

Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Singleton has almost the same pros and cons as global variables. Although they're super-handy, they break the modularity of your code.

Does singleton allow lazy initialization?

Singleton Class in Java using Lazy LoadingThe instance could be initialized only when the Singleton Class is used for the first time. Doing so creates the instance of the Singleton class in the JVM Java Virtual Machine during the execution of the method, which gives access to the instance, for the first time.


1 Answers

The init gets called only the first time you invoke MyClass.shared

At that point the instance of MyClass is saved inside the shared static constant.

Example

Let's consider this Singleton class

final class Singleton {
    static let shared = Singleton()
    private init() {
        print("Singleton initialized")
    }

    var count = 0
}

Now let's look at the output into the console

enter image description here

As you can see the Singleton initialized string is printed only once. This means the init is only called once.

Note: Of course I assumed the implementation of your Singleton class is correct.

like image 83
Luca Angeletti Avatar answered Sep 23 '22 23:09

Luca Angeletti