if/else statements as expressions in Swift
Swift 5.9 introduced a nice feature that lets us use if/else statements as expressions. We can return values from functions, assign values to variables, and declare variables using if/else, where previously we needed to use a ternary operator, Swift's definite initialization with assignment on each branch or even closures.
Let's say we have a game where a player can score points, and based on the number of points, we assign them a rank.
func playerRank(points: Int) -> String {
let rank =
if points >= 1000 { "Gold" }
else if points >= 500 { "Silver" }
else if points >= 100 { "Bronze" }
else { "Unranked" }
return rank
}
let playerPoints = 650
print(playerRank(points: playerPoints)) // Prints "Silver"
In this example, the playerRank()
function takes the number of points a player has scored as input and returns a string that represents the player's rank. The rank is determined by an if/else expression, and the value of the chosen branch becomes the value of the overall expression.
Note, that each branch of if/else must be a single expression, and each expression, when type checked independently, must produce the same type. This ensures easy type checking and clear reasoning about the code.
This feature applies to switch statements as well. You can find out more in the related Swift proposal on if and switch expressions.