你如何在swift中写下以下内容?
static ClassName* singleCommon = nil;
+ (ClassName*)sharedInstance {
@synchronized(singleCommon) {
if(!singleCommon) singleCommon = [[ClassName alloc] init];
}
return singleCommon;
}
答案 0 :(得分:1)
我通常在Swift中使用sharedInstance,如下所示:
private let _sharedInstance = SomeClass()
class SomeClass: NSObject {
class var sharedInstance: SomeClass {
get {
return _sharedInstance
}
}
}
这是一篇讨论这个问题的博文: http://thatthinginswift.com/singletons/
答案 1 :(得分:1)
一个好的解决方案是:
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static var instance: Singleton?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = Singleton()
}
return Static.instance!
}
}
解决方案和解释来自: http://code.martinrue.com