Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct implementation of cellForRowAtIndexPath in Swift 2.0

Is the following implementation of cellForRowAtIndexPath the technically correct best-practice way taking into account the unwrapping of optionals

 class MyTableViewController: UITableViewController {
        var cell : UITableViewCell?
         // other methods here 
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        cell = tableView.dequeueReusableCellWithIdentifier("ItemCell")! as UITableViewCell
        let myItem = items[indexPath.row]

        cell!.textLabel?.text = myItem.name
        cell!.detailTextLabel?.text = myItem.addedByUser

        return cell!
      }

    }
like image 252
Arunabh Das Avatar asked Dec 17 '15 22:12

Arunabh Das


1 Answers

In Swift 2 dequeueReusableCellWithIdentifier is declared as

func dequeueReusableCellWithIdentifier(_ identifier: String,
                      forIndexPath indexPath: NSIndexPath) -> UITableViewCell

and cellForRowAtIndexPath is declared as

func tableView(tableView: UITableView, 
             cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

You see, No optionals!

The code can be reduced to

class MyTableViewController: UITableViewController {

   // other methods here 
   override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath)
     let myItem = items[indexPath.row]

     cell.textLabel?.text = myItem.name
     cell.detailTextLabel?.text = myItem.addedByUser

     return cell
  }
}

In case of a custom table view cell the cell can be forced casted to the custom type.

let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) as! CustomCell

It's always a good idea to option-click on the symbol or use Quick Help to look up the exact signature.

like image 167
vadian Avatar answered Oct 13 '22 00:10

vadian