Alexey K Alexey K - 1 year ago 176
Swift Question

Swift - init in singleton class?

I have a singleton class

for management work with third party sdk. Inside singleton I have

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

Answer Source

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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download