Matching based on class - great for prepareForSegue

suggest change

You can also make a switch statement switch based on the class of the thing you’re switching on.

An example where this is useful is prepareForSegue. Switching on the segue identifier is fragile. If the storyboard later renames that identifier, the code breaks. Segues to several scenes of the same view-controller class also cannot be told apart by identifier alone.

A Swift switch can match the destination's type with case let name as Type:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  switch segue.destinationViewController {
    case let fooViewController as FooViewController:
      fooViewController.delegate = self

    case let barViewController as BarViewController:
      barViewController.data = data

    default:
      break
  }
}

In Swift 3 the method and property names changed. sender is Any?, and the destination property is destination:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  switch segue.destination {
    case let fooViewController as FooViewController:
      fooViewController.delegate = self

    case let barViewController as BarViewController:
      barViewController.data = data

    default:
      break
  }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents