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

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.

主站蜘蛛池模板: 永川市| 建昌县| 白银市| 赣州市| 沅江市| 沙坪坝区| 商城县| 湄潭县| 深水埗区| 五家渠市| 韶关市| 都兰县| 朔州市| 河津市| 安仁县| 渭南市| 登封市| 修文县| 海晏县| 新晃| 栾川县| 博野县| 明溪县| 措美县| 宕昌县| 林州市| 舟山市| 开阳县| 昌平区| 呼伦贝尔市| 时尚| 壶关县| 和平区| 湾仔区| 稷山县| 温泉县| 长白| 晋中市| 蓝田县| 福泉市| 湘乡市|