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

  • 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
主站蜘蛛池模板: 焉耆| 原平市| 黑河市| 同仁县| 库尔勒市| 嵩明县| 德庆县| 西丰县| 南丹县| 辽阳县| 阿坝县| 阿鲁科尔沁旗| 遵义县| 灯塔市| 监利县| 灌云县| 湾仔区| 安陆市| 丰镇市| 玉溪市| 邢台市| 临武县| 隆林| 新乡市| 宝鸡市| 深州市| 上杭县| 嘉黎县| 武清区| 梅河口市| 自贡市| 定日县| 梁平县| 浮梁县| 邵武市| 青河县| 敦煌市| 易门县| 荣昌县| 广州市| 衡阳县|