Pattern matching with one sided ranges.

Pattern matching works really well with one sided ranges in switch statements, but you should be mindful of the one hitch that it has.

While writing a switch case, be careful to add a default case since you have to make your switch case exhaustive and since one sided ranges are infinite now, adding a default case becomes mandatory:

let selectedNumber = 7
switch selectedNumber {
case ..<0 :
print("You have selected a negative number.")
case 0... :
print("You have selected a positive number")
default :
break
}

Here, note that we have already covered all the scenarios in the first 2 cases:

  • Case 1: All negative numbers up to -1
  • Case 2: All positive numbers from 0 onward

Hence, we simply break out the switch statement in the default case.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset