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

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
主站蜘蛛池模板: 清镇市| 吉木乃县| 济阳县| 牙克石市| 永城市| 通城县| 安陆市| 松溪县| 宝山区| 万全县| 黔江区| 宿州市| 社会| 威远县| 德惠市| 哈密市| 涪陵区| 德州市| 崇礼县| 惠安县| 贵德县| 广丰县| 金川县| 同仁县| 晋城| 威信县| 新竹市| 宜丰县| 旬阳县| 孝昌县| 咸丰县| 浠水县| 镇平县| 嘉鱼县| 徐州市| 仙桃市| 海阳市| 苏州市| 克什克腾旗| 砀山县| 牙克石市|