NEW BOOK! SwiftUI Fundamentals: The essential guide to SwiftUI core concepts and APIs. Learn more ...NEW BOOK! SwiftUI Fundamentals:Master SwiftUI core concepts and APIs. Learn more...
Quick Tip Icon
Quick Tip

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.

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

Level up your Swift skills!$35

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

Swift Gemsby Natalia Panferova

  • 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

Level up your Swift skills!

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

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

Swift Gems

by Natalia Panferova

$35