swift中的dispatch_once singleton

Isu*_*uru 0 singleton grand-central-dispatch ios swift

我需要将以下Objective-C代码转换为Swift.

static RWBasicCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
  sizingCell = [self.tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
});
Run Code Online (Sandbox Code Playgroud)

我怎么做?我用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!
    }
}
Run Code Online (Sandbox Code Playgroud)

但这是为了返回一个班级.

Nat*_*ook 8

这是来自Ray Wenderlich的教程,对吗?Swift没有可以作用于函数的静态变量,但是你可以在函数中嵌入一个类型,并赋予它静态变量.这是该方法开头的Swift等效版本:

func heightForBasicCellAtIndexPath(indexPath: NSIndexPath) -> CGFloat {
    struct Static {
        static var sizingCell: RWBasicCell?
    }

    if Static.sizingCell == nil {
        Static.sizingCell = tableView.dequeueReusableCellWithIdentifier(RWBasicCellIdentifier) as RWBasicCell
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)