Tutorial by Examples

let number = 3 switch number { case 1: print("One!") case 2: print("Two!") case 3: print("Three!") default: print("Not One, Two or Three") } switch statements also work with data types other than integers. They work with any data t...
A single case in a switch statement can match on multiple values. let number = 3 switch number { case 1, 2: print("One or Two!") case 3: print("Three!") case 4, 5, 6: print("Four, Five or Six!") default: print("Not One, Two, Three, Four, F...
A single case in a switch statement can match a range of values. let number = 20 switch number { case 0: print("Zero") case 1..<10: print("Between One and Ten") case 10..<20: print("Between Ten and Twenty") case 20..<30: print("Be...
The where statement may be used within a switch case match to add additional criteria required for a positive match. The following example checks not only for the range, but also if the number is odd or even: switch (temperature) { case 0...49 where temperature % 2 == 0: print(&quot...
You can create a tuple and use a switch like so: var str: String? = "hi" var x: Int? = 5 switch (str, x) { case (.Some,.Some): print("Both have values") case (.Some, nil): print("String has a value") case (nil, .Some): print("Int has a value&...
Switch statement make use of partial matching. let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 5) switch (coordinates) { case (0, 0, 0): // 1 print("Origin") case (_, 0, 0): // 2 print("On the x-axis.") case (0, _, 0): // 3 print("On the y-axis.") ca...
It is worth noting that in swift, unlike other languages people are familiar with, there is an implicit break at the end of each case statement. In order to follow through to the next case (i.e. have multiple cases execute) you need to use fallthrough statement. switch(value) { case 'one': //...
The Switch statement works very well with Enum values enum CarModel { case Standard, Fast, VeryFast } let car = CarModel.Standard switch car { case .Standard: print("Standard") case .Fast: print("Fast") case .VeryFast: print("VeryFast") } Since we ...
Some example cases when the result is an optional. var result: AnyObject? = someMethod() switch result { case nil: print("result is nothing") case is String: print("result is a String") case _ as Double: print("result is not nil, any value that is a Dou...
Switches can switch on tuples: public typealias mdyTuple = (month: Int, day: Int, year: Int) let fredsBirthday = (month: 4, day: 3, year: 1973) switch theMDY { //You can match on a literal tuple: case (fredsBirthday): message = "\(date) \(prefix) the day Fred was born"...
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 ...

Page 1 of 1