Alexey K Alexey K - 1 month ago 6
Swift Question

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()
?

Answer

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.