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)
Written by Wim Haanstra
Related protips
1 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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Extension
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#