Black Friday 2024 deal: 30% off our Swift and SwiftUI books! Learn more ...Black Friday 2024 deal:30% off our Swift and SwiftUI books >>
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.

As someone who has worked extensively with Swift, I've gathered many insights over the years. I've compiled them in my book Swift Gems, which is packed with advanced tips and techniques to help intermediate and advanced Swift developers enhance their coding skills. From optimizing collections and handling strings to mastering asynchronous programming and debugging, "Swift Gems" provides practical advice to elevate your Swift development. Grab your copy of Swift Gems and let's explore the advanced techniques together.

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

Black Friday 2024 offer: 30% off!$35$25

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
Black Friday 2024 offer: 30% off!

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$25