lojovw
Last Updated: March 18, 2016
·
8.799K
· depl0y
187f3356c852d3962517834d20aa18f7 normal

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() } }
Say Thanks
Respond

1 Response
Add your response

27424
Rfinn2

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 ·