Skip to content

Instantly share code, notes, and snippets.

@acecilia
Last active June 11, 2018 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acecilia/ec9af4401231b23b17057fc29c2c751b to your computer and use it in GitHub Desktop.
Save acecilia/ec9af4401231b23b17057fc29c2c751b to your computer and use it in GitHub Desktop.
// Crashing: force unwrapping
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "Cell", for: indexPath) as! CustomCell
cell.customLabel.text = "Title"
return cell
}
// Crashing: fatal error
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(
withIdentifier: "Cell", for: indexPath) as? CustomCell else {
fatalError("The registered type for the cell does not match the casting")
}
cell.customLabel.text = "Title"
return cell
}
// Silent error: not customizing the cell if the cast fails
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "Cell", for: indexPath)
if let cell = cell as? CustomCell {
cell.customLabel.text = "Title"
}
return cell
}
// Silent error: return a default value for the cell
// in case the cast fails: an empty cell
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "Cell", for: indexPath) as? CustomCell
cell?.customLabel.text = "Title"
return cell ?? UITableViewCell()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment