Skip to content
DeveloperMemos

Unlocking Swift 5.9's New Power: Simplifying Code with If and Switch Expressions

Swift, Swift 5.9, Code Expressions1 min read

In the realm of Swift, readability and conciseness have long been cherished qualities, and Swift 5.9 brings us an innovative way to achieve this. The introduction of if and switch expressions in Swift 5.9 empowers developers to create shorter and more legible code. Much like Swift 5.1's capacity to omit the return keyword in single expressions within closures, these new expressions provide a streamlined and elegant way to write code. In this article, we'll delve into the realm of if and switch expressions in Swift with unique insights and fresh code examples.

Embracing if Statements as Expressions

Traditionally, when you needed to assign a value based on a condition, you might have resorted to an if-else statement, like this:

1var weather: String
2
3if isRaining {
4 weather = "Rainy"
5} else {
6 weather = "Sunny"
7}

While this approach is clear and functional, it can become cumbersome in functions with multiple similar assignments. Some developers often lean on the ternary operator, which can make the code more concise but sometimes less readable. However, Swift 5.9 introduces a game-changer - if statements as expressions. Here's how you can employ them:

1let weather: String = if isRaining {
2 "Rainy"
3} else {
4 "Sunny"
5}

In this case, the behavior is akin to omitting the return keyword. The if statement branch should contain a single expression, and you can even format it over multiple lines for clarity. Nevertheless, it's essential to note that you can't use if statements as expressions without an else statement.

Simplified Switch Expressions

Switch statements in Swift often involve writing the return keyword on a new line for every case, which, while readable, can seem a bit verbose:

1var meal: String {
2 switch timeOfDay {
3 case .morning:
4 return "Breakfast"
5 case .noon:
6 return "Lunch"
7 case .evening:
8 return "Dinner"
9 }
10}

However, in Swift 5.9, you can streamline your code and omit the return keyword, making it even more concise:

1var meal: String {
2 switch timeOfDay {
3 case .morning: "Breakfast"
4 case .noon: "Lunch"
5 case .evening: "Dinner"
6 }
7}

These switch expressions are a great way to simplify your code, making it more elegant and less verbose while retaining clarity.

In summary, Swift 5.9's if and switch expressions provide you with the tools to reduce code length while enhancing readability. Similar to the elimination of the return keyword inside closures, you can now omit it inside single-expression if and switch statements. These language enhancements offer a more efficient way to craft clean and concise code in Swift.

Feel free to explore and experiment with these new features in Swift 5.9 to see how they can benefit your coding projects!