Correct implementation of cellForRowAtIndexPath in Swift 2.0

≯℡__Kan透↙ 提交于 2021-02-07 06:24:28

问题


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

    }

回答1:


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.



来源:https://stackoverflow.com/questions/34345142/correct-implementation-of-cellforrowatindexpath-in-swift-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!