ForEach Syntax in Swift, Kotlin and JavaScript

ForEach is a common pattern in programming modern programming languages. Prior to ForEach, the standard approach to iterating over an array of objects was to use a for loop stepping from the first index to the last.

ForEach syntax has extra utility in languages that support many types of collections: a list iterated using ForEach doesn't need to have sequential indexes!

Swift

Iterating over a list of objects in a collection: forEach

1let array = ["Hello", "World"]
2for word in array {
3  print(word)
4}

To access the element index within the forEach execution block, use the enumerated function. This can be done using either for or forEach. Note that when using enumerated, the index emitted is just a counter, so it will be emit an accurate accessor value only when used with zero-based arrays.

1let array = ["Hello", "World"]
2array.enumerated().forEach { (index, name) in
3  print("\(word) is at index \(index)")
4}
5
6for (index, name) in array.enumerated() {
7    print("\(index): \(name)")
8}

Notable is a similarly named--but not the same--language construct used in SwiftUI for iterating over a collection that emits a list of SwiftUI views: ForEach

 1var filters = ["First", "Second", "Third"]()
 2
 3// Emit three SwiftUI Buttons
 4ForEach(filters, id: \.self) { choice in
 5    Button(action: {
 6        print("Filter selected: \(choice)")
 7    }) {
 8        Text(choice)
 9    }
10}

SwiftUI ForEach requires that each item in the collection be unique, and the id property can be passed in-line as in this example.

If the collection of items passed to ForEach conforms to the Swift Identifiable protocol, then it isn't necessary to specify the id property, since Swift will implicitly know which property to use to distinguish the uniqueness of items in the list.

Kotlin

Kotlin's forEach syntax is virtually identical to Swift's.

1val array = listOf("Hello", "World")
2
3array.forEach { word ->
4  print(word)
5}

To access the array index within the execution block:

1val array = listOf("Hello", "World")
2
3array.forEachIndexed{ index, word ->
4  print("$word is at index $index")
5}

JavaScript

In JavaScript, the syntax is similar to other languages, but note that ForEach is actually a function call, so don't forget the parentheses!

1const array = [ "Hello", "World"]
2
3array.forEach(word => {
4  console.log(word)
5})

While forEach is more modern and and a more natural way to think about iterating over lists, I often find using old-school index iteration in JavaScript simpler when used with arrays, since it doesn't have the complexity of being a function call executing a block in a separate scope:

1const array = [ "Hello", "World"]
2
3for (let i=0; i < array.length; i++) {
4  console.log(array[i])
5}