-
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
break
for 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
default
case 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) where age > 55:
println("Personage is \(name) whose age is \(age) who is also older than 55")
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)")
}
This will allow you to switch for a class or subclass. You can use is
or as
:
-
is
just checks the type. -
as
checks the type, but also allows you to use thelet
binding.
This would be useful for a func that responds to @IBAction
or UITapGestureRecognizer
, for example.
let selectedView = sender
switch selectedView {
case is UIButton:
println("Selection is a button")
case let label as UILabel:
println("Selection is a label with this text: \(label.text)")
case let tableView as UITableView:
println("It's a Table View with \(tableView.numberOfSections()) sections")
default:
println("Sender is neither a button, a label, or a tableView")
}