3
votes

I am trying to create UITableViewCell type variable with swift, these are my codes:

 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
}

In 7th line if (cell == nil), it gives me an error that Value of type 'UITableViewCell' can never be nil, comparison isn't allowed. It can't be replaced by if ( !cell ). How should I fix the codes?

3

3 Answers

3
votes

If you really want to use the outdated method tableView.dequeueReusableCellWithIdentifier(_:) you can do it like this:

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
}

But you should preferably use dequeueReusableCellWithIdentifier(_:forIndexPath:) which never returns nil.
It is used along with registerClass(_:forCellReuseIdentifier:) and registerNib(_:forCellReuseIdentifier:).

0
votes

According to Apple docs, dequeReusableCellWithIdentifier returns an optional value :

 func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell?

But in your code, you explicitly unwrap this value because your cell object is an UITableViewCell object.

You should use - dequeueReusableCellWithIdentifier:forIndexPath: : its return value is not optional thus you don't have to unwrap your cell.

0
votes

Because the non optional type cannot be compared with nil (Only optional variables contains nil value). Like if you want to check nil then just use that way. i implemented it in Playground

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")
}