Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice to prevent an instance from init() in a Singleton class in Swift

I learned from Using Swift with Cocoa and Objective-C that a singleton can be created like this:

class Singleton {
    static let sharedInstance = Singleton()
}

But as I learned, we should also prevent an instance created from the constructor. Creating an instance of the class Singleton outside the class scope, like the statement below, should be prevented:

let inst = Singleton()

So, could I do just like this:

class Singleton {
    static let sharedInstance = Singleton()
    private init() {}
}

Or, is there any better practice?

like image 356
Lujun Weng Avatar asked Dec 21 '15 03:12

Lujun Weng


People also ask

How do you clear a singleton instance in Swift?

You don't destroy a singleton. A singleton is created the first time anyone needs it, and is never destroyed as long as the application lives.

How do you declare a singleton in Swift?

In Swift, Singleton is a design pattern that ensures a class can have only one object. Such a class is called singleton class. An initializer allows us to instantiate an object of a class. And, making the initializer of a class restricts the object creation of the class from outside of the class.

Can we Deinit 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.


1 Answers

The way that you have suggested is the way that I always implemented it.

public class Singleton
{
    static public let sharedInstance = Singleton();

    private init()
    {

    }
}

It's the cleanest solution for a Singleton pattern that I've ever found. Now that in Swift 2 you can specify accessibility it does actually prevent you from calling something like:

var mySingleton = Singleton();

Doing so results in a compile time error:

'Singleton' cannot be constructed because it has no accessible initializers
like image 85
Jacob Joz Avatar answered Oct 13 '22 01:10

Jacob Joz