Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/93.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 定义';UITableViewCell';Swift 2.0中的变量_Ios_Swift_Uitableview - Fatal编程技术网

Ios 定义';UITableViewCell';Swift 2.0中的变量

Ios 定义';UITableViewCell';Swift 2.0中的变量,ios,swift,uitableview,Ios,Swift,Uitableview,我正在尝试使用swift创建UITableViewCell类型变量,以下是我的代码: func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dwarves.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&

我正在尝试使用swift创建UITableViewCell类型变量,以下是我的代码: func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dwarves.count }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier)! as UITableViewCell
    if (cell == nil) {
        cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: simpleTableIdentifier)
    }

    cell.textLabel?.text = dwarves[indexPath.row]
    return cell
}

在第7行中,如果(cell==nil),它会给我一个错误,类型为“UITableViewCell”的值永远不能为零,不允许进行比较。
如果(!cell)
,则不能将其替换为。如何修复代码?

因为非可选类型不能与
nil
进行比较(只有可选变量包含
nil
值)。比如,如果你想检查
nil
,那么就用那种方式。我在
游乐场

let tableView = UITableView()
let index = NSIndexPath()
var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("")
//then make check for nil if you want
if (cell == nil) {
    print("its nil")
} else  {
    print("not nil")
}

如果您确实想使用过时的方法
tableView.dequeueReusableCellWithIdentifier(:)
,您可以这样做:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) ?? UITableViewCell(style: .Default, reuseIdentifier: simpleTableIdentifier)
    cell.textLabel?.text = dwarves[indexPath.row]

    return cell
}
但最好使用永不返回
nil

它与and一起使用。

根据,
dequeReusableCellWithIdentifier
返回可选值:

 func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell?
但在代码中,您显式地展开此值,因为您的单元格对象是
UITableViewCell
对象


您应该使用
-dequeueReusableCellWithIdentifier:forIndexPath:
:它的返回值不是可选的,因此您不必打开您的单元格。

是的,我对“单元格”进行了审查,它收到了零。但是,如果可能的值是零,那么如何审查所有可能的值呢。