-
Notifications
You must be signed in to change notification settings - Fork 3
Overview_Switch
Tom Ryan edited this page Jun 3, 2015
·
4 revisions
A basic switch statement resembles the switch in Objective-C, however there are some differences:
- switches don't require
breakfor every case. - switches must be all-encompassing -- Either by
- providing a case for all values (in the case of
Enums) - provide a 'default:' case.
- providing a case for all values (in the case of
let val = 10
switch val {
case 1: println("One")
case 10: println("Ten")
default: println("Some other number")
}
let val = 10
switch val {
case 0...9: println("It's a single digit")
case 10...99: println("We've got double-digits")
case 100...999: println("Whoa, triple-digit number")
default: println("There are 4 or more digits here")
}
enum Result {
case Value(Int)
case Error(String)
}
For Enums with associated values, the only way to access those values is through a switch statement.
let result = Result.Value(1)
switch result {
case let .Value(val):
println("Success! The value is \(val)")
case .Error(let err):
println("Error! And here's the error: \(err)")
}
Note you don't need to use a
defaultcase in this example, since the switch statement is exhaustive.
let person = ("Fred", 39)
switch person {
case ("Fred", let age):
println("Person is Fred, whose age is \(age) years")
case (_, 39)
println("Person is 39 years old")
case (_, 20...29):
println("Person is in their twenties")
case (let name, _):
println("Person's name is \(name), who is not in their twenties")
case (_, _):
println("I couldn't be bothered checking on the name or age")
}
switching while binding the case statements
let personage = ("Edward Malthus", 55)
switch personage {
case let (name, age):
println("Personage is \(name) whose age is \(age)")
case (let name, let age):
println("This is another way to get \(name) and \(age)")
case (_, let age):
println("I couldn't care less about the name, but I know now that their age is \(age)")
}