官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 桐乡市| 唐河县| 鄢陵县| 乐亭县| 婺源县| 白沙| 乌兰浩特市| 靖边县| 永德县| 信阳市| 长治县| 西峡县| 石景山区| 九寨沟县| 塔河县| 达孜县| 偃师市| 黔西| 慈溪市| 广汉市| 军事| 来宾市| 天气| 景宁| 乌什县| 益阳市| 肃北| 芮城县| 上犹县| 彭山县| 南和县| 西丰县| 平潭县| 屏南县| 正阳县| 赣州市| 江源县| 台湾省| 菏泽市| 澄迈县| 南丹县|