- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 190字
- 2021-07-02 14:45:10
Iterating, mapping, and reducing
Starting with Swift 3, C-style statements that are usually used when iterating through arrays have been removed, so you can no longer write the following:
for var i = 0; i < otherDoubles.count; i++ {
let element = otherDoubles[i]
}
Instead, we use more powerful syntax:
A simple iterator is as follows:
for value in doubles {
print("\(value)") // 1.0, 2.0, 3.0
}
You can use an enumerator as follows:
for (idx, value) in doubles.enumerated() {
print("\(idx) -> \(value)") // 0 -> 1.0, 1 -> 2.0, 2 -> 3.0
}
Similarly, you can use the forEach method that will invoke a closure for each element, passing it as the first parameter:
doubles.forEach { value in
// do something with the value
}
Next, we can transform the current array into another array of the same dimensions, through the map method:
let twices = doubles.map { value in
return "\(value * 2.0)"
} // twices is [String] == ["2.0", "4.0", "6.0"]
Finally, when you need to change the dimensions of your array, change the type, or any other transformation, you can use the reduce method to do the following:
- Calculate a sum, as follows:
let sum = doubles.reduce(0) { $0 + $1 }
- Create a new array, larger than the original one, as follows:
let doubleDoubles = doubles.reduce([]) { $0 + [$1, $1] }
doubleDoubles == [1.0, 1.0, 2.0, 2.0, 3.0, 3.0] // true
推薦閱讀
- 公有云容器化指南:騰訊云TKE實戰與應用
- Greenplum:從大數據戰略到實現
- Creating Mobile Apps with Sencha Touch 2
- 使用GitOps實現Kubernetes的持續部署:模式、流程及工具
- 分布式數據庫系統:大數據時代新型數據庫技術(第3版)
- 企業大數據系統構建實戰:技術、架構、實施與應用
- MySQL從入門到精通(第3版)
- Sybase數據庫在UNIX、Windows上的實施和管理
- Python金融數據分析(原書第2版)
- 數據庫技術實用教程
- 深入淺出 Hyperscan:高性能正則表達式算法原理與設計
- 大數據技術入門
- Gideros Mobile Game Development
- 數據庫應用系統技術
- Scratch 2.0 Game Development HOTSHOT