Swift 5.9: Switch & If Expressions
Since Swift 5.9 switch
and if
statements can now be used as expressions. This is a nice addition since in some cases it saves us a little code to write.
Switch expression
An easy example is a function that returns a value based on a switch statement. Prior to Swift 5.9 we used something like this:
func getStatus(code: Int) -> String {
switch code {
case 200...299: return "Ok"
case 404: return "Not Found"
...
default: return "Status Code: \(code)"
}
}
Notice that each case
needs an explicit return but now we can just omit that entirely as long as we return the same Type
in all cases:
func getStatus(code: Int) -> String {
switch code {
case 200...299: "Ok"
case 404: "Not Found"
...
default: "Status Code: \(code)"
}
}
If expression
This also works great for if
statements. But although we are pretty used to the ternary operators this can make things more clear for more complicated statements:
let status = if code == 404 {
"Not Found"
} else if code < 300 && code >= 200 {
"Ok"
} else {
"Status Code: \(code)"
}
With the use of ternary operators this would look something like this:
let status = code == 404 ? "Not Found" : (code < 300 && code >= 200) ? "Ok" : "Status Code: \(code)"
I think we can all agree that the use of an if
expression makes more sense in this case due to better readability.
After all it really depends on you own preferences and code style but it's nice to have multiple options for different scenarios. But remember that in case of the expression the return value's type must match across all cases/branches.