- Reactive Programming with Swift 4
- Navdeep Singh
- 172字
- 2021-06-24 18:58:00
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...]
推薦閱讀
- The DevOps 2.3 Toolkit
- 小程序實戰視頻課:微信小程序開發全案精講
- Oracle數據庫從入門到運維實戰
- Java持續交付
- Java Web開發技術教程
- PHP+MySQL+Dreamweaver動態網站開發實例教程
- 西門子S7-200 SMART PLC編程從入門到實踐
- Java程序設計案例教程
- Java 9 Programming By Example
- Android應用開發實戰(第2版)
- MyBatis 3源碼深度解析
- ASP.NET Web API Security Essentials
- Mastering ASP.NET Core 2.0
- Python 3快速入門與實戰
- Docker on Windows