我读到在Swift中实现单例模式需要创建一个结构或全局常量作为" Swift不支持类型存储属性"
final class BackupServer {
let name:String;
private var data = [DataItem]();
private init(name:String) {
self.name = name;
globalLogger.log("Created new server \(name)");
}
func backup(item:DataItem) {
data.append(item);
globalLogger.log("\(name) backed up item of type \(item.type.rawValue)");
}
func getData() -> [DataItem]{
return data;
}
class var server:BackupServer {
struct SingletonWrapper {
static let singleton = BackupServer(name:"MainServer");
}
return SingletonWrapper.singleton;
}
}
这在Swift2中是否仍然如此?我正在学习如何根据自己的兴趣在Swift中实现Singleton模式,并且不需要被告知它是一种反模式。 docs似乎表示存储的类型属性是可能的
答案 0 :(得分:4)
我在Swift中创建单例的最佳方法如下:
class SingletonClass {
static let sharedInstance = SingletonClass()
private init() {} //This prevents others from using the default '()' initializer for this class.
}
您可以在此处阅读完整说明: http://krakendev.io/blog/the-right-way-to-write-a-singleton
答案 1 :(得分:1)
在docs的其他地方,有一个关于单身人士的部分,我没见过:
在Swift中,您可以简单地使用静态类型属性,即使在同时跨多个线程访问时,也可以保证只延迟初始化一次:
class Singleton {
static let sharedInstance = Singleton()
}
如果需要在初始化之外执行其他设置,可以将闭包调用的结果分配给全局常量:
class Singleton {
static let sharedInstance: Singleton = {
let instance = Singleton()
// setup code
return instance
}()
}