if/else statements as expressions in Swift 5.9

Related Articles

Swift 5.9 that comes with Xcode 15 introduces a nice feature, it allows us to use if/else statements as expressions. We can return values ​​from functions, assign values ​​to variables and declare variables using if/else, where before we had to use the third operator, Swift’s distinct initialization with assignment on any 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 him 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))  

In this example, the playerRank() The function takes the number of points a player scored as input and returns a string representing the player’s rating. The rank is determined by an if/else expression, and the value of the selected branch becomes the value of the total expression.

Note that each if/else branch must be a single expression, and each expression, when a type is independently annotated, must produce the same type. This ensures easy type checking and clear reasoning about the code.

This new feature of Swift 5.9 also applies to switch statements. You can find out more in the related Swift proposal if and replace phrases.

Integrating SwiftUI in UIKit apps by Natalia Panprovova book cover
WWDC23 proposal

our book “Integrating SwiftUI in UIKit apps” now 40% discount!

Discover different ways to adopt SwiftUI in existing UIKit projects and take full advantage of the new iOS 16 frameworks and APIs such as Swift Charts.

The sale is active until 19.6.


Popular Articles