Use if/else and switch statements as expressions in Swift 5.9

Swift 5.9 brought an arsenal of enhancements to the already powerful and versatile language, but there's one in particular that has been long anticipated by developers. Swift now allows the use of if/else and switch statements as expressions, presenting an avenue to write more readable and concise code. This feature is a game-changer in initializing variables based on complex conditions without resorting to difficult-to-read ternary expressions.

If/Else Statements as Expressions

Consider the situation where you want to initialize a let variable based on a complex condition. Traditionally, this would necessitate using compound ternary expressions that can quickly become convoluted. Here's an example of what that may look like:

let result = (condition1 ? value1 :
              condition2 ? value2 :
              condition3 ? value3 :

Now, with Swift 5.9, you can leverage if/else expressions. This allows you to use a more familiar and readable chain of if statements. Below is the transformed code:

let result = if condition1 {
} else if condition2 {
} else if condition3 {
} else {

The updated code is considerably more readable and easier to follow, enhancing the overall maintainability of the codebase.

Global Variables and Stored Properties

The ability to use if/else and switch statements as expressions is particularly useful when initializing a global variable or a stored property. In previous versions of Swift, if your initialization required complex conditionals or switch statements, you would need to wrap them in a closure and execute it immediately, as shown:

let animalSound: String = {
    switch animal {
    case .dog:
        return "Bark"
    case .cat:
        return "Meow"
    case .cow:
        return "Moo"
        return "Unknown sound"

Now, with the power of if expressions, you can simply eliminate that clutter, leaving you with much neater code:

let animalSound: String = switch animal {
    case .dog:
    case .cat:
    case .cow:
        "Unknown sound"

Swift 5.9 brings a significant enhancement in readability and conciseness by allowing if/else and switch statements to be used as expressions. This can drastically improve your code structure, making it easier to read, understand, and maintain.

Happy coding!

XOXO, Christian 👨🏻‍💻