Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining 'UITableViewCell' variable in Swift 2.0

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?

like image 848
pakgwan luk Avatar asked Jul 03 '26 13:07

pakgwan luk


1 Answers

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:).

like image 112
fluidsonic Avatar answered Jul 06 '26 05:07

fluidsonic