- 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...]
推薦閱讀
- Web前端開發技術:HTML、CSS、JavaScript(第3版)
- AWS Serverless架構:使用AWS從傳統部署方式向Serverless架構遷移
- Interactive Data Visualization with Python
- Android Studio Essentials
- Java程序員面試算法寶典
- Web Application Development with MEAN
- R的極客理想:工具篇
- Windows Server 2016 Automation with PowerShell Cookbook(Second Edition)
- SQL經典實例(第2版)
- 利用Python進行數據分析
- PHP+MySQL動態網站開發從入門到精通(視頻教學版)
- Web程序設計:ASP.NET(第2版)
- SQL Server 2012 數據庫應用教程(第3版)
- 3D Printing Designs:Octopus Pencil Holder
- Python程序設計教程