Statement switch
- can use any data type: Int, String(case sensitive), Tuple…
- cases must be exhaustive (use
default
or list all options)
- cases can use range operators (ie.
0...3
, 4...6
)
- no implicit fallthrough →
break
is understood
// -> Error: 404
var statusCode = 404
var errorString = "Error: "
switch statusCode {
case 100:
errorString += "Info, 100."
// compound case
case 201, 204:
errorString += "No content 2xx."
// range case
case 400...417:
errorString += "\(statusCode)"
default:
errorString = "\(statusCode) Unknown."
}
statusCode
passed into switch print via string interpolation
- if multiple cases are valid, only 1st evaluated is executed unless
fallthrough
is used
Tuple Matching switch
// -> That dog is 7
let dogInfo1 = (7, "Fido")
switch dogInfo1 {
// no, due to case sensitivity
case (7, "fido"):
"fido is 7"
// "_" -> wildcard
case (7, _):
"That dog is 7"
default:
"Default dog"
}
Value Bindings switch var let
- assign a var/con within a
case
that is only valid at that point
- bound values are automatically evaluated as true/correct
// -> My dog Maxx is 8
let dogInfo2 = (7, "Max")
switch dogInfo2 {
// 1st tuple value bound to age
case (let age, "max"):
"That's Max who is \(age)"
// replaces default|assigns multiple
case var (age, name):
age += 1
name = "Maxx"
"My dog \(name) is \(age)"
}
- move
var
outside parenthesis to bind all values
default
isn’t necessary if all options are bound
Value Bindings and where
clause
- allows use of a conditional on bound vars/cons
// -> Spot is 7
let dogInfo3 = (7, "Spot")
switch dogInfo3 {
case let (_, name) where name == "spot":
"Is that spot?"
case let (age, name) where age == 7:
"\(name) is \(age)"
default:
"default dog"
}
default
still needed due to the where
clause
if case
and implied where clause
- focuses on a single condition, doesn’t use
default
// -> Cool and...
let age = 25
if case 18...35 = age, age >= 21 {
print("Cool and can drink")
}
// if case converted to a basic if
if (age >= 18) && (age <= 35) && (age >= 21) {
print("Cool and can drink")
}