What is the best practice of preventing 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 as follows:

class Singleton {
    static let sharedInstance = Singleton()
}

But, as I found out, we must also prevent the creation of an instance from the constructor. Creating an instance of the Singleton class outside the scope of the class, like the instruction below, should be prevented:

let inst = Singleton()

So, can I do like this:

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

Or is there any best practice?

+4
source share
2 answers

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

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

    private init()
    {

    }
}

Singleton, - . , Swift 2 , - :

var mySingleton = Singleton();

:

'Singleton' cannot be constructed because it has no accessible initializers
+7
private let singletonInstance = Singleton()

final class Singleton: NSObject {
    static func getInstance() -> Singleton {
        return singletonInstance
    }
}

. , ( ).

0

Source: https://habr.com/ru/post/1621042/


All Articles