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

One sided ranges

Swift 4 makes it optional to provide a starting index or finishing index of ranges, as used with earlier versions of Swift.

With earlier versions of Swift, you had to do the following to use ranges:

let contactNames = [“Alex”, “Ravi”, “Moin”, “Vlad”, “Mark”]
let firstTwoContacts = contactNames[0..<2]
let lastThreeContacts = contactNames[2..<contactNames.count]
print(firstTwoContacts)
print(lastThreeContacts)

You will get the result as follows:

["Alex", "Ravi"] , for [0..<2]
["Moin", "Vlad", "Mark"], for [2..<contactNames.count]

However, with Swift 4, you no longer have to be constrained to lower bounds or upper bounds of the range mentioned in the for loop mentioned earlier in the code example. You can now use a one sided range where the missing side will automatically be treated as the start or end of a sequence:

let firstTwoContacts = contactNames[..<2]
let lastThreeContacts = contactNames[2...]
print(firstTwoContacts)
print(lastThreeContacts)

You will get the result as shown:

["Alex", "Ravi"] , for [..<2]
["Moin", "Vlad", "Mark"] for [2...]
主站蜘蛛池模板: 平乡县| 同心县| 德令哈市| 根河市| 普陀区| 大名县| 临潭县| 深水埗区| 兰坪| 迭部县| 偃师市| 寻甸| 丰宁| 怀集县| 平阴县| 麻阳| 华宁县| 原平市| 敦化市| 突泉县| 盐亭县| 荥经县| 土默特右旗| 卢湾区| 嘉峪关市| 洪泽县| 定日县| 双城市| 石景山区| 蕉岭县| 剑河县| 灵石县| 原阳县| 溆浦县| 庆城县| 且末县| 文昌市| 张家口市| 贵定县| 嘉禾县| 淅川县|