Swift - Matching a Range of Numbers using switch statement

Introduction

You can perform range matching using the Switch statement.

The following code shows how you can match a range of numbers against a variable/constant:

Demo

var percentage = 85
switch percentage {
       case 0...20:
           print("Group 1")
       case 21...40:
           print("Group 2")
       case 41...60:
           print("Group 3")
       case 61...80:
           print("Group 4")
       case 81...100:
           print("Group 5")
       default:// www.j  a  v  a 2s  .c  om
           print("Invalid percentage")
}

Result

The range of numbers that you are matching need not be integers.

You can also specify floating-point numbers.

The closed ranged operator (represented by ... ) specifies the range of numbers that you are comparing.

Related Topic