Xcode 6 Beta5:为什么' UITableViewCell'不是' NSNumber&#39 ;?的子类型?

时间:2014-08-11 11:52:37

标签: ios uitableview swift

我尝试在实现cellForRowAtIndexPath协议的ViewController中实现函数UITableViewDataSource

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    ...

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell;
        if !cell {
            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
        }
        cell.textLabel.text = "row \(indexPath.row)";
        cell.detailTextLabel.text = "row details \(indexPath.row)"
        return cell;
    }

它是来自Objective-c代码对应物的忠实翻译(我想)。

但是,swift编译器会标记此错误消息:"' UITableViewCell'不是' NSNumber'"

的子类型

enter image description here

如果我将实现更改为

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell;

    cell.textLabel.text = "row \(indexPath.row)";
    // cell.detailTextLabel.text = "row details \(indexPath.row)"
    return cell;
}

编译器错误消失了,应用程序似乎按照我的预期工作。

我的问题:

1)为什么swift编译器发出此错误消息?

2)测试变量cell的正确语法是否为null?在这里,NSNumber显然很快。是因为!运算符吗?

3)检查cell是否为空是否有意义?我想当我在as UITableViewCell电话中使用dequeueReusableCellWithIdentifier时,我已经排除了零的可能性。 swift因此保证函数dequeueReusableCellWithIdentifier总是返回UITableViewCell吗?它与objective-c行为不同。

1 个答案:

答案 0 :(得分:4)

你必须明确地测试nil。请参阅XCode 6 Beta 5的发行说明。

if cell != nil {
    ...
}

但编译器消息具有误导性。

  

Optionals不再符合BooleanType(以前的LogicValue)协议,因此它们也是如此   可能不再用于代替布尔表达式(必须明确地与它们进行比较)   v!= nil)。