iOS Development

Optional Error Handling

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Error Handling

#include <stdio.h>

int main() {
    printf("Hello World!
    return 0;

However, Error Handling is Important

  • Prevent crashes
  • Provide expected behavior, even when things could go wrong
    • E.g., resource issues
  • You don't fully understand a function/method call or API until you understand its error handling

Swift Optionals

  • Optionals can be nil
var n:Int?
  • Non-optionals cannot

Unsafe Behavior

  • Note: All Objective-C objects can be nil, and the frameworks we are using are based on Objective-C
  • So almost anything from the framework will be optional
self.detailDescriptionLabel!.text = self.detailItem!.description
  • Crash if self.detailItem or self.detailDescriptionLabel are nil
  • Explicit unwrapping should be avoided at all costs

Checking first

if let detail = self.detailItem {
      if let label = self.detailDescriptionLabel {
           label.text = detail.description
  • Safe
  • Verbose

Short-Circuit Evaluation

Instead of:

if i >= 0 && i <= ar.count {
    if ar[i] == 5 {

we can write:

if i >= 0 && i <= ar.count && ar[i] == 5 {

Optional Chaining

self.detailDescriptionLabel?.text = self.detailItem?.description
  • Semantics: Evaluate as long as possible, until nil is found
  • Fails gracefully
  • If any subpart is nil, entire result is nil

Optional Chaining to the Rescue

self.detailDescriptionLabel?.text = self.detailItem?.description
  • Safe
  • Compact code
  • Just as short as assuming the best
  • No special action when errors occur, but that is okay

Model Decisions

  • In our model, do we use optionals or not?