Stuart Breckenridge

The Correct Way to Initialise a UITableViewCell

Below I present four options for initialising a UITableViewCell. Of these options, I tend to use the second option (or a close variant) in production code, and for brevity, option 4 in sample code.

What do you prefer? Are there other, safer options available?

Option 1:

var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
    cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
}
return cell

Option 2:

guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) else {
    let newCell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
    return newCell
}
return cell

Option 3:

if let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) {
    return cell
} else {
    let newCell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
    return newCell
}

Option 4:

let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
return cell

— Supported by —