我需要将以下 Objective-C 代码转换为 Swift。
static RWBasicCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [self.tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
});
我该怎么做?我用 Google 搜索并找到了这个例子。
class SingletonC {
class var sharedInstance : SingletonC {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : SingletonC? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = SingletonC()
}
return Static.instance!
}
}
但它是为了返回一个类的单个。
最佳答案
这是来自 this Ray Wenderlich tutorial , 正确的? Swift 没有可以作用域为函数的静态变量,但是您可以在函数中嵌套一个类型,并给它静态变量。这是该方法开始的 Swift 等效版本:
func heightForBasicCellAtIndexPath(indexPath: NSIndexPath) -> CGFloat {
struct Static {
static var sizingCell: RWBasicCell?
}
if Static.sizingCell == nil {
Static.sizingCell = tableView.dequeueReusableCellWithIdentifier(RWBasicCellIdentifier) as RWBasicCell
}
// ...
}
关于ios - Swift 中的 dispatch_once 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27486600/