- 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
推薦閱讀
- Greenplum:從大數(shù)據(jù)戰(zhàn)略到實(shí)現(xiàn)
- Unity 5.x Game AI Programming Cookbook
- 工業(yè)大數(shù)據(jù)分析算法實(shí)戰(zhàn)
- 數(shù)據(jù)庫(kù)應(yīng)用基礎(chǔ)教程(Visual FoxPro 9.0)
- 深度剖析Hadoop HDFS
- 大數(shù)據(jù)Hadoop 3.X分布式處理實(shí)戰(zhàn)
- 數(shù)據(jù)庫(kù)技術(shù)及應(yīng)用教程
- Spark大數(shù)據(jù)編程實(shí)用教程
- “互聯(lián)網(wǎng)+”時(shí)代立體化計(jì)算機(jī)組
- Hadoop大數(shù)據(jù)開發(fā)案例教程與項(xiàng)目實(shí)戰(zhàn)(在線實(shí)驗(yàn)+在線自測(cè))
- Google Cloud Platform for Developers
- Mastering LOB Development for Silverlight 5:A Case Study in Action
- 爬蟲實(shí)戰(zhàn):從數(shù)據(jù)到產(chǎn)品
- 機(jī)器學(xué)習(xí):實(shí)用案例解析
- 大數(shù)據(jù)測(cè)試技術(shù):數(shù)據(jù)采集、分析與測(cè)試實(shí)踐(在線實(shí)驗(yàn)+在線自測(cè))