.forEach()
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 thedictionary
.
Example
Below is an example of using .forEach()
with a dictionary:
let fruits = ["apple": 3, "banana": 2, "cherry": 5]fruits.forEach { (key, value) inprint("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
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Swift on Codecademy
- Skill path
Build iOS Apps with SwiftUI
Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.Includes 7 CoursesWith CertificateBeginner Friendly13 hours - Free course
Learn Swift
A powerful programming language developed by Apple for iOS, macOS, and more.Beginner Friendly12 hours