Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/122.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 用Swift发送一次单件_Ios_Swift_Singleton_Grand Central Dispatch - Fatal编程技术网

Ios 用Swift发送一次单件

Ios 用Swift发送一次单件,ios,swift,singleton,grand-central-dispatch,Ios,Swift,Singleton,Grand Central Dispatch,我需要将以下Objective-C代码转换为Swift static RWBasicCell *sizingCell = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sizingCell = [self.tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"]; }); 我该怎么做?我在谷歌上找到了这个例子 class Si

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

static RWBasicCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
  sizingCell = [self.tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
});
我该怎么做?我在谷歌上找到了这个例子

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!
    }
}
但是它是用来返回一个类的单个元素的。

这是来自,对吗?Swift没有可以作用于函数的静态变量,但是您可以在函数中嵌套一个类型,并给它一个静态变量。下面是该方法开始的Swift等效版本:

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

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

    // ...
}

对我正在用Swift做那个教程。非常感谢。这个主题的其他问题与类的共享单例实例有关,而这是关于函数范围内的静态变量。在这种情况下,初始化不同于始终可用的单例,因此不同的问题似乎很有用。