Swift 5.9 introduces some improvements that will allow a more clear and less tedious to write code.

This changes affect if else and switch statements.

Let’s see them more in detail.

If-else

The ternary syntax is really handy and allows us to return a result based on a condition in a let statement.

This is really useful in simple cases that involves only one condition but if there are more nested conditions it can become really hard to read, like the example below.

let bullet = isRoot && (count == 0 || !willExpand) ? ""

             : count == 0 ? "- "

             : maxDepth <= 0 ? "▹ " : "▿ "

To make the above code more readable we could wrap it in a closure and use if else statements. But in this case we should use the return keyword every time we need to return a value.

let bullet = {

    if isRoot && (count == 0 || !willExpand) { return "" }

    else if count == 0 { return "- " }

    else if maxDepth <= 0 { return "▹ " }

    else { return "▿ " }

}()

The new syntax avoids all of these problems.

Now the if else statement can start right after the let declaration without any closure or ternary syntax.

let bullet = if isRoot && (count == 0 || !willExpand) { "" }

             else if count == 0 { "- " }

             else if maxDepth <= 0 { "▹ " }

             else { "▿ " }

The new syntax allows return keyword omission but, if you prefer, you can still add return wherever you need it.

Of course you can still use the two techniques above in Swift 5.9 if you wish.

Switch

So far Swift has allowed us to omit the return keyword in funcs and computed vars when the body is a single expression, however we must use the return keyword in switch statements if we need to return a value.

This was needed up until now.

With Swift 5.9 you can omit the return keyword even in switch statements!

enum Color {

  case red

  case green

  case blue

  var color: Color {

    switch self {

    case .red: Color.red

    case .green: Color.green

    case .blue: Color.blue

    }

  }

}

func width(_ x: Unicode.Scalar) -> Int {

  switch x.value {

  case 0..<0x80: 1

  case 0x80..<0x0800: 2

  case 0x0800..<0x1_0000: 3

  default: 4

  }

}

Resources

Some examples in this article are taken from SE-0380.

Conclusion

These are really nice additions to Swift 5.9 that will improve the syntax and will make our code more readable and less tedious to write.

What are you thoughts about this? Tweet me @franceleonidev and share your opinion.

Source link