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

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.

主站蜘蛛池模板: 合山市| 湟中县| 拉萨市| 海丰县| 永胜县| 京山县| 双鸭山市| 全椒县| 武城县| 裕民县| 阳山县| 延庆县| 宝山区| 望谟县| 伊金霍洛旗| 崇文区| 柘荣县| 大理市| 密云县| 江都市| 钟祥市| 水城县| 巴林左旗| 新宁县| 莎车县| 共和县| 松潘县| 临泉县| 台安县| 赣州市| 永川市| 自贡市| 佛冈县| 大余县| 彰化县| 临西县| 板桥市| 页游| 嘉峪关市| 琼结县| 柘荣县|