NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. Lear more...
Quick Tip Icon
Quick Tip

if/else statements as expressions in Swift 5.9

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 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 new Swift 5.9 feature applies to switch statements as well. You can find out more in the related Swift proposal on if and switch expressions.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Check out our new book!

Swift Gems

100+ tips to take your Swift code to the next level

Swift Gems

100+ tips to take your Swift code to the next level

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift