Anthony Kong
Anthony Kong

Reputation: 40754

Xcode 6 Beta5: Why 'UITableViewCell' is not a subtype of 'NSNumber'?

I tried to implement the function cellForRowAtIndexPath in my ViewController that implements the UITableViewDataSource protocol:

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;
    }

It is a faithful translation from the objective-c code counterpart (I suppose).

However, swift compiler flags this error message: "'UITableViewCell' is not a subtype of 'NSNumber'"

enter image description here

If I changed the implementation to

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;
}

The compiler error is gone and the App seems to work as I expect.

My question:

1) Why swift compiler emitted this error message?

2) What is the proper syntax to test variable cell is null or not? Apparently swift is expected a NSNumber here. Is it because of the ! operator?

3) Does it make sense to check if cell is null? I suppose when I used as UITableViewCell in the dequeueReusableCellWithIdentifier call, I have already excluded the possibility of nil. Does swift thereby guarantee the function dequeueReusableCellWithIdentifier to always return a UITableViewCell? It is different from objective-c behaviour.

Upvotes: 3

Views: 628

Answers (1)

zisoft
zisoft

Reputation: 23078

You have to explictly test for nil. See the release notes for XCode 6 Beta 5.

if cell != nil {
    ...
}

The compiler message is misleading, though.

Optionals no longer conform to the BooleanType (formerly LogicValue) protocol, so they may no longer be used in place of boolean expressions (they must be explicitly compared with v != nil).

Upvotes: 4

Related Questions