Swift .forEach()
Published Oct 11, 2022Updated Mar 17, 2023
Contribute to Docs
The .forEach() method loops over the array, calling the closure function on each element in the array. As each element is iterated over, some action can be performed on it.
This method will operate on all elements of the array and cannot be escaped using a break or continue call. Returning a value in the body of the closure will only return that value out of the body and not the declaring method body. The .forEach() method is commonly used when all elements are to be manipulated by the loop or to display the purpose of the loop to others reading the code.
Syntax
arrayName.forEach(body)
Example
var topBabyNames = ["Liam", "Jackson"]topBabyNames.forEach { name inprint("\(name) is the coolest name.")}// Output:// Liam is the coolest name.// Jackson is the coolest name.
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
- Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
- Includes 7 Courses
- With Certificate
- Beginner Friendly.13 hours
- A powerful programming language developed by Apple for iOS, macOS, and more.
- Beginner Friendly.12 hours