lojovw
Last Updated: March 18, 2016
·
13.12K
· 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() } }

1 Response
Add your response

27424

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 ·