Swift is a pretty functional language and functional languages are all about expressions not statements which is why switch pattern matching puzzles me.
All the example are something like this:
switch x {
case > 0:
print("positive")
case < 0:
print("negative")
case 0:
print("zero")
}
But I want to do something like this:
let result = switch x {
case > 0:
"positive"
case < 0:
"negative"
case 0:
"zero"
}
Currently the only way i can see to do it is:
var result: String?
switch x {
case > 0:
result = "positive"
case < 0:
result = "negative"
case 0:
result = "zero"
}
if let s = result {
//...
}
Which is obviously no where near as elegant as the 'expression' based switch statement. Are there any work around or alternatives or is this something apple need to do to enhance the language?
Switch statement cannot be directly used as an expression in Swift. But, there is a workaround to do what you want. It is possible to write the switch statement inside a closure like this:
let result : String = {
switch x {
case _ where x > 0:
return "positive"
case _ where x < 0:
return "negative"
default:
return "zero"
}
}()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With