Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Swift Dictionary

  1. Home
  2. Swift Dictionary
  3. Array.reduce() / forEach() / enumerated()

Array.reduce() / forEach() / enumerated()

Swift arrays provide reduce(_:_:) to aggregate elements into a single value, and forEach() to iterate over all elements. Use enumerated() to access both index and element at once, and zip() to pair elements from two arrays.

Syntax

// Aggregate (specify an initial value and a combining closure)
array.reduce(initialValue) { accumulated, element in
    return newAccumulatedValue
}
array.reduce(0, +)  // Concise form using an operator

// Iterate over all elements (no return value)
array.forEach { element in
    // process
}

// Enumerate with index
for (index, element) in array.enumerated() { }

// Pair elements from two arrays
zip(array1, array2)

Method List

MethodDescription
array.reduce(initialValue, operation)Starting from an initial value, applies an operation to each element and aggregates them into a single value.
array.reduce(into: initialValue) { result, element in }An efficient variant of reduce that mutates the accumulated value in place using inout.
array.forEach { element in }Executes a closure for every element. You cannot use break inside the closure.
array.enumerated()Returns a sequence of (index, element) pairs.
zip(array1, array2)Returns a sequence of pairs by matching elements from two sequences.
zip(array1, array2).map { }Transforms corresponding elements from two arrays.

Sample Code

// reduce: calculate the sum
let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(0) { $0 + $1 }
print(sum)  // 15

// Concise form using an operator
let sumShort = numbers.reduce(0, +)
print(sumShort)  // 15

// Find the maximum value
let maxVal = numbers.reduce(Int.min) { max($0, $1) }
print(maxVal)  // 5

// reduce(into:): build a dictionary
let words = ["apple", "banana", "apricot", "blueberry", "avocado"]
let grouped = words.reduce(into: [Character: [String]]()) { dict, word in
    let key = word.first!
    dict[key, default: []].append(word)
}
print(grouped["a"] ?? [])  // ["apple", "apricot", "avocado"]
print(grouped["b"] ?? [])  // ["banana", "blueberry"]

// forEach: process all elements
["Swift", "Kotlin", "Rust"].forEach { lang in
    print("Language: \(lang)")
}

// enumerated: iterate with index
let fruits = ["apple", "orange", "grape"]
for (i, fruit) in fruits.enumerated() {
    print("\(i + 1). \(fruit)")
}

// zip: pair elements from two arrays
let names = ["Taro", "Hanako", "Jiro"]
let scores = [85, 92, 78]
for (name, score) in zip(names, scores) {
    print("\(name): \(score) points")
}

Notes

forEach is equivalent to a for-in loop, but because it uses a closure, you cannot use break or continue inside it. If you need to stop iteration early, use a for-in loop instead.

reduce(into:) is more efficient than the standard reduce when building a dictionary or array as the result. zip stops at the shorter sequence. If the two arrays have different lengths, the extra elements are silently discarded.

For searching arrays, see array.contains() / firstIndex() / lastIndex().

If you find any errors or copyright issues, please .