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

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
主站蜘蛛池模板: 垣曲县| 兰州市| 饶平县| 南丰县| 富宁县| 荥经县| 黎平县| 钟祥市| 建德市| 湟源县| 凌云县| 广丰县| 巢湖市| 文成县| 邯郸市| 怀安县| 辽源市| 永春县| 珲春市| 关岭| 青海省| 阳新县| 门源| 资源县| 杂多县| 广饶县| 石景山区| 重庆市| 扎兰屯市| 城固县| 新建县| 彝良县| 冀州市| 顺昌县| 枣阳市| 屏山县| 太白县| 尼木县| 梁河县| 二连浩特市| 芒康县|