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

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...]
主站蜘蛛池模板: 九龙城区| 海阳市| 浦县| 定结县| 天气| 甘洛县| 梁山县| 卢龙县| 乡城县| 正定县| 开远市| 苍南县| 丽江市| 扶余县| 上高县| 博白县| 克什克腾旗| 竹北市| 宁城县| 郑州市| 福海县| 山阴县| 延吉市| 夹江县| 奉节县| 铜梁县| 祁门县| 池州市| 汶上县| 桦甸市| 连江县| 龙江县| 保山市| 临武县| 鹤峰县| 黎川县| 上饶县| 定兴县| 景宁| 自治县| 嫩江县|