timpone
timpone

Reputation: 19979

how to return one of two types of custom table view cells in cellForRowAtIndexPath in Swift 1.2

I am migrating some objective-c code to Swift. I was able to do something very similar to this in objective-c but it is telling me that I have a "Use of unresolved identifier 'tableViewCell'"; returning it in the method doesn't help.

  override func viewDidLoad() {
    super.viewDidLoad()

    self.mainTV.registerClass(EKMenuHeaderCell.self, forCellReuseIdentifier: "MenuHeaderCell")
    self.mainTV.registerClass(EKMenuItemCell.self, forCellReuseIdentifier: "MenuItemCell")
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let tmpTableItem = self.tableItems[indexPath.row]
  if let menuHeader = tmpTableItem as? EKMenuHeader {
    let tableViewCell = tableView.dequeueReusableCellWithIdentifier("MenuHeaderCell", forIndexPath: indexPath) as! EKMenuHeaderCell
    tableViewCell.selectionStyle = UITableViewCellSelectionStyle.None
    tableViewCell.updateCell(menuHeader)
    // return tableViewCell    // doesn't work
  } else if let menuItem = tmpTableItem as? EKMenuItem {
    let tableViewCell = tableView.dequeueReusableCellWithIdentifier("MenuItemCell", forIndexPath: indexPath) as! EKMenuItemCell
    tableViewCell.updateCell(menuItem)
    // return tableViewCell    // doesn't work
  }
  return tableViewCell
}

How would I return two different types of custom cells like this in Swift 1.2?

Upvotes: 1

Views: 1212

Answers (1)

GoZoner
GoZoner

Reputation: 70245

You are returning tableViewCell at the end of the method, but your two variables for tableViewCell are scoped to the if consequent and if alternate - thus invisible at the return

To fix it you'll need to ensure that you return a UITableViewCell in all paths through your code or you fatal. So, for example:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let tmpTableItem = self.tableItems[indexPath.row]

  if let menuHeader = tmpTableItem as? EKMenuHeader {
    let tableViewCell = tableView.dequeueReusableCellWithIdentifier("MenuHeaderCell", forIndexPath: indexPath) as! EKMenuHeaderCell
    tableViewCell.selectionStyle = UITableViewCellSelectionStyle.None
    tableViewCell.updateCell(menuHeader)
    return tableViewCell

  } else if let menuItem = tmpTableItem as? EKMenuItem {
    let tableViewCell = tableView.dequeueReusableCellWithIdentifier("MenuItemCell", forIndexPath: indexPath) as! EKMenuItemCell
    tableViewCell.updateCell(menuItem)
    return tableViewCell
  }

  // If you can return something meaningful, do so; otherwise fatal.
  else { preconditionFailure ("unexpected cell type") }
}

Upvotes: 4

Related Questions