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