Swift Switch with Ranges for Cases

We can specify range of values for cases in switch statement when the switch expression is a number.

In this tutorial, we will learn how to specify range of values for cases in a Switch statement.

Example

In the following program, we will write a switch statement where the expression evaluates to a number, and in the case blocks, we match it against ranges.

main.swift

</>
Copy
var x = 10

switch x {
case 0...5:
    print("x is in [0,5]")
case 6...10:
    print("x is in [6,10]")
default:
    print("x is something else.")
}

Output

Swift Switch with Ranges for Cases - Example

Conclusion

In this Swift Tutorial, we learned how to write a switch statement with cases having range of values.