'for' or '.forEach'

I learn something new every day. I have an array of indices. They way I would normally access each of the array elements referenced by the indices is this:

    for index in offsets
    {
      let item = items[index]
      ...do something with 'item'...
    }

Yesterday, I learned that I could do this:

offsets.forEach
{ index in
  let item = items[index]
  ...do something with 'item'...
} 

So my question is, is either one of these methods better than the other, or are they equivalent?

Always trying to learn.

Put your cursor on the forEach method and then hold the Command key down and select “Jump to Definition”
The documentation is above the method and pretty much covers what you are asking.

1 Like

Thank Chris – it sure does. Since I’m not using continue or return, I guess they’re equivalent.

@PeteTheGolfer

These are basically the same except (like you said)

forEach” works like “ for in” but the basic difference is, you can’t use break and continue statement to exit from the closure for forEach

The .forEach is what’s called a higher order function, you can learn more here

https://levelup.gitconnected.com/higher-order-functions-in-swift-35861620ad1

2 Likes

Good article. Thanks for the suggestion.

Correct me if I’m wrong, but I’m assuming that, if either method can be used, there’s no advantage to using one over the other.

Other than when you use yourArray.forEach you cannot use “break” or “continue” nor can you “return” early from the loop if there is condition set within that loop that is true. .forEach will iterate over every element. For example, consider the following:

let words = ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf"]
words.forEach { word in
    //  Skips printing Alpha but continues printing the remainder
    if word == "Alpha" {
        return
    }
    print(word)
}

As the comment suggests the return merely causes it to go to the next element.

I have rarely seen it used. That’s not to say that you can’t.

See this brief article by John Sundell for more reasons to choose one over the other: Picking between a for loop and forEach

I find .forEach useful when chaining operations in a functional way. It just reads better that way.

So instead of:

let alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
let consonants = alphabet.filter { !["a","e","i","o","u"].contains($0) }
for letter in consonants {
    print(letter.uppercased())
}

you can do:

let alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
alphabet
    .filter { !["a","e","i","o","u"].contains($0) }
    .forEach { print($0.uppercased()) }

Amazing, there’s actually a document addressing the exact question I asked.

Thanks for the help. I can’t say I’m less confused, but at least I’m more informed.