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?
let result: String. The compiler verifies that a value is assigned to it before the variable is used. - Martin R