Swift - Switches with range

Introduction

Switches in Swift can use ranges as cases.

You can create code that runs when the value you're testing falls between certain ranges:

Demo

var someNumber = 15 
switch someNumber { 
case 0...10: // ww w. j av a  2  s  .  c  o  m
    print("Number is between 0 and 10") 
case 11...20: 
    print("Number is between 11 and 20") 
case 21: 
    print("Numer is 21!") 
default: 
    print("Number is something else") 
}

Result

If multiple cases in a switch statement overlap-for example, case 0...10 and case 5...15-then the first matching case will be used.

Related Topic