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 in prepareForSegue
. I used to switch based on the segue identifier, but that's fragile. if you change your storyboard later and rename the segue identifier, it breaks your code. Or, if you use segues to multiple instances same view controller class (but different storyboard scenes) then you can't use the segue identifier to figure out the class of the destination.
Swift switch statements to the rescue.
Use Swift case let var as Class
syntax, like this:
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 sytax has changed slightly:
override func prepare(for 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
}
}