我试图将其转换为swift:
+ (instancetype)sharedGameKitHelper
{
static GameKitHelper *sharedGameKitHelper;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedGameKitHelper = [[GameKitHelper alloc] init];
});
return sharedGameKitHelper;
}
现在我对Objective-C没有任何经验所以我使用了这个转换器:Objectivec2swift.com它给了我这个:
class func sharedGameKitHelper() -> Self {
var sharedGameKitHelper: GameKitHelper?
var onceToken: dispatch_once_t
dispatch_once(onceToken, {() -> Void in
sharedGameKitHelper = GameKitHelper()
})
return sharedGameKitHelper!
}
它给了我一些错误,我不知道如何处理它,所以我很感激这里的一些帮助。
错误:
答案 0 :(得分:0)
为了与旧的C API兼容,需要使用罕见的&
运算符来处理参数的性质地址。 onceToken需要一个独特的价值。您还需要显式类型Self
。
最后,为了实现紧凑性,您可以使用尾随闭包语法和推断的函数签名。
class GameKitHelper {
static var onceToken: dispatch_once_t = 1
class func sharedGameKitHelper() -> GameKitHelper {
var sharedGameKitHelper: GameKitHelper?
dispatch_once(&onceToken) { sharedGameKitHelper = GameKitHelper() }
return sharedGameKitHelper!
}
}
然而,这种方法是非惯用的&过于复杂。参见:
http://krakendev.io/blog/the-right-way-to-write-a-singleton
在那里引用回到SO: