什么是在Swift的Singleton类中阻止init()实例的最佳实践

Luj*_*eng 5 singleton ios swift

我从使用Swift with Cocoa和Objective-C中学到了可以像这样创建单例:

class Singleton {
    static let sharedInstance = Singleton()
}
Run Code Online (Sandbox Code Playgroud)

但是,据我所知,我们还应该阻止从构造函数创建的实例.应该阻止在类范围外创建类Singleton的实例,如下面的语句:

let inst = Singleton()
Run Code Online (Sandbox Code Playgroud)

那么,我可以这样做:

class Singleton {
    static let sharedInstance = Singleton()
    private init() {}
}
Run Code Online (Sandbox Code Playgroud)

或者,有没有更好的做法?

Jac*_*Joz 8

你建议的方式是我总是实现它的方式.

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

    private init()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

这是我发现的Singleton模式最干净的解决方案.现在在Swift 2中你可以指定它实际上阻止你调用类似的东西:

var mySingleton = Singleton();
Run Code Online (Sandbox Code Playgroud)

这样做会导致编译时错误:

'Singleton' cannot be constructed because it has no accessible initializers
Run Code Online (Sandbox Code Playgroud)