.forEach()

Anonymous contributor's avatar
Anonymous contributor
Published Sep 18, 2024
Contribute to Docs

The .forEach() method is used to iterate over each key-value pair in a Swift dictionary. It applies a specified closure to each key-value pair, allowing for actions or computations to be performed on each element without manual key access. This method is particularly useful for executing side effects or processing elements concisely and functionally.

Syntax

dictionary.forEach { (key, value) in
    // Code to execute for each key-value pair
}
  • dictionary: The variable name for the dictionary instance.
  • { (key, value) in ... }: Defines a closure where key and value are parameters representing each key-value pair from the dictionary.

Example

Below is an example of using .forEach() with a dictionary:

let fruits = ["apple": 3, "banana": 2, "cherry": 5]
fruits.forEach { (key, value) in
print("There are \(value) \(key)s.")
}

The code above produces the following output:

There are 3 apples.
There are 2 bananas.
There are 5 cherrys.

Note: The order of key-value pairs iterated over in a Swift dictionary using forEach is not guaranteed and may vary between executions.

All contributors

Contribute to Docs

Learn Swift on Codecademy