fs_tigre fs_tigre - 3 months ago 7
iOS Question

Why Can Singleton classes can be used as regular classes

I was under the impression that the main reason for using singletons was to make sure that only one instance could be created in a program. I thought that the compiler wouldn't let you create instances of a singleton as if it would be a regular class.

In the following code I have a singleton where I'm creating multiple instances of it and it behaves as a regular class, but for some reason I was expecting an error.

What makes a singleton different than a regular class if it lets you create multiple instances?

// singleton class
class Car {
static let sharedCar = Car()

func run(){
print("Running")
}
}
// use
Car.sharedCar.run()

// other instances- I was expecting an error here
var jetta = Car()
jetta.run()

var cobalt = Car()
cobalt.run()


What am I missing here, can someone explain singletons?

Answer

I thought that the compiler wouldn't let you create instances of a singleton as if it would be a regular class.

There is no language feature called "singleton", it is an idiomatic pattern. If you leave your implementation of singleton open for instantiations from outside, there is nothing the compiler can do about that.

In the following code I have a singleton where I'm creating multiple instances of it and it behaves as a regular class, but for some reason I was expecting an error.

You should add a private init to make sure there are no external instantiations:

class Car {
    static let sharedCar = Car()

    func run(){
        print("Running")
    }

    private init() {
    }
}

Now you are the only one who can instantiate your class. Users of Car class outside of your code are forced to rely on sharedCar instance that you create for them.