我从使用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)
或者,有没有更好的做法?