James James - 6 months ago 41
iOS Question

Swift: Set custom UITableViewCell class inside if statement

I'm a Swift newbie and struggling to do something pretty simple.

I want to change the class of a tableViewCell when its tapped. After a lot of Googling I'm now trying to do this by setting a boolean flag (in a dict) and checking the value to determine which class to use.

I've come unstuck with Swift basics of trying to set a variable inside an if statement:

// I think I need to instantiate the cell variable here to be used inside
// and after the if statement but don't know what class type to use.
// I've tried lots of "var cell: xxx = yyy" variations but no luck

if selectedRows[indexPath.row] == true {
let cell = tableView.dequeueReusableCellWithIdentifier("Tier3CellExpanded", forIndexPath: indexPath) as! Tier3CellExpanded
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("Tier3Cell", forIndexPath: indexPath) as! Tier3TableViewCell
}
let image = UIImage(named: entry.thumbnail)
cell.thumbImageView.image = image
cell.busNameLabel.text = entry.busName
cell.busAddressLabel.text = entry.address
return cell


If anyone could point me in the right direction that would be great.

Answer

I'm just expanding on Charles A. 's answer to show you how to declare cell outside the if statement but still use 2 different cell types.

//All shared properities would belong to this class
var cell: MySuperclassCellsInheritFrom
if selectedRows[indexPath.row] {
    cell = tableView.dequeueReusableCellWithIdentifier("Tier3CellExpanded", forIndexPath: indexPath) as! Tier3CellExpanded
    //Set properties specific to Tier3CellExpanded
}
else {
    cell = tableView.dequeueReusableCellWithIdentifier("Tier3Cell", forIndexPath: indexPath) as! Tier3TableViewCell
    //Set properties specific to Tier3TableViewCell
}

// Configure cell
// Properties that both subclasses share can be set here

return cell

This is possible since we declared cell as UITableViewCell and then cast it after dequeing with identifiers. The cast is possible because the cells you are dequeuing are subclasses of UITableViewCell. So after casting you can now set all of that subclasses individual properties.

This method is useful in case there is other code that you want to apply to both cells that you won't need to duplicate in each if statement such as backgroundColor changes or other base UITableViewCell properties.