Photo by 傅甬 华 on Unsplash

Could not cast value of type UITableViewCell to AppName.CustomCellName

Table views in iOS are ubiquitous when developing apps in the Apple ecosystem. It does most of the hard work not only manipulating the data but also integrating your app seamlessly with the operational system.

Still, advanced configurations could incur into sometimes cryptic error messages that are hard to debug. Such is the case when setting up custom cells.

Adding cells to TableView

One way of adding cells to the table view is using dequeueReusableCellWithIdentifier.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  var cell:CustomCell = tableView.dequeueReusableCellWithIdentifier("customCell") as! CustomCell

  let data = dataArray[indexPath.row]["Data"] as? String
  cell.cellTitle.text = data

  return cell
}

Here you may be confronted with an error message of the type:

Could not cast value of type 'UITableViewCell' (0x1321e4b72) to 'MyApp.CustomCell' (0x10e3418f1)

Solutions

There are a few things one can check in this scenario:

  1. See if your table is linked to your class, usually by:
@IBOutlet weak var tableView: UITableView!
  1. Register custom table view cell:
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

Note that you use “UITableViewCell” and the identifier “cell” even if your custom cell has different class and id.

  1. Dequeue your cell in cellForRowAtIndexPath:
let cell: MessageCell = self.tableView.dequeueReusableCellWithIdentifier("messageCell") as! MessageCell

Now use the correct cell identifier.

May 09, 2020.