Alexey K Alexey K - 4 months ago 35
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()


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.