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!
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With