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

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
主站蜘蛛池模板: 沾益县| 广宗县| 茌平县| 寻乌县| 宜兰市| 洪江市| 慈溪市| 咸阳市| 黎川县| 黎平县| 留坝县| 遵化市| 那曲县| 洪洞县| 延川县| 景德镇市| 安平县| 饶平县| 沛县| 砚山县| 塘沽区| 瑞昌市| 碌曲县| 保德县| 永清县| 巴林左旗| 漯河市| 江阴市| 海林市| 南涧| 郑州市| 上林县| 安庆市| 榆社县| 读书| 黄平县| 舒城县| 广南县| 莒南县| 南京市| 武鸣县|