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

Working with ranges

Ranges come in two flavors: Range and ClosedRange. The difference between Range and ClosedRange is the inclusion of the upper bound. In a ClosedRange, the upper bound is included; in Range, it isn't.

If you want to include all numbers between 0 and 10, not including 10, you can represent it in two ways, as follows:

let range1 = 0..<10
let range2 = 0...9

range1.contains(10) // false

The two ranges are equivalent, and they contain the same numbers. They read differently and carry different meanings, however depending on what you want to express, you may want to pick one over the other. Ranges work with the Comparable protocol, which means that any type that conforms to this Comparable protocol is suited for creating ranges.

For example, you could create a Range type of Strings, as follows:

let uppercased = "A"..."Z"
uppercased.contains("C") // true
uppercased.contains("c") // false

You can also use the ~= operator, which is an alias for the contains method:

uppercased ~= "Z" // true
主站蜘蛛池模板: 闸北区| 隆德县| 蛟河市| 双牌县| 织金县| 和顺县| 游戏| 万荣县| 罗平县| 徐汇区| 麟游县| 闽侯县| 武鸣县| 松江区| 镇康县| 阿拉善盟| 乐东| 永安市| 桓台县| 新兴县| 宁乡县| 怀集县| 曲水县| 柯坪县| 天全县| 舟曲县| 彩票| 正宁县| 靖州| 成安县| 清涧县| 三都| 金堂县| 凤凰县| 嘉兴市| 朝阳市| 吉林市| 会东县| 九江县| 周至县| 石棉县|