Last Updated: November 19, 2020
·
15.64K
· depl0y

forEach on an Array in Swift

If you want to easily loop through an array and perform some action on each item. Sort of how you do it in Ruby.

extension Array {

    func forEach(iterator: (T) -> Void) -> Array {
        for item in self {
            iterator(item)
        }

        return self;
    }

}

Now you can do the following:

var items: [MyItem] = ....

items.forEach { if ($0.someProperty) { doCoolStuff() } }

Related protips:

Some simple Swift Extensions (Strip HTML, RGB Color, Color invert, Dismiss modal segue)

1 Response
Add your response

As of Swift 2, forEach(_:) is a builtin method on SequenceType objects, so you don't need to define an extension on Array.

On the other hand, it is more usual in Swift to iterate directly on the Array:

for item in items {
    if item.someProperty {
        doCoolStuff()
    }
}
over 1 year ago ·