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

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
主站蜘蛛池模板: 泽州县| 平武县| 莱芜市| 昭苏县| 高邑县| 抚顺市| 长泰县| 湘阴县| 漳平市| 汉中市| 灌阳县| 邵武市| 买车| 渭南市| 信阳市| 慈利县| 宁晋县| 察雅县| 深水埗区| 甘肃省| 合江县| 瑞安市| 壤塘县| 昌图县| 安泽县| 长宁县| 新晃| 海林市| 南昌市| 大英县| 扎囊县| 竹北市| 望都县| 怀安县| 兴和县| 马山县| 阿拉善盟| 泗水县| 庄浪县| 达孜县| 博乐市|