LoginSignup
3
3

More than 5 years have passed since last update.

[Swift]Java8 Stream API の forEach ライクなメソッドを作る

Last updated at Posted at 2015-03-13

Java8 の Stream API にある forEach メソッドを Swift で再現してみました。

instruction
extension Array {

    func forEach(consumer: (Element) -> Void) -> Void {
        for obj in self {
            consumer(obj as Element)
        }
    }
}

次のような使い方ができます。

sample1
["apple", "orange", "pear"].forEach { data in print(data) }

ちなみに次のプログラムと同じことをしています。

sample2
for data : String in ["apple", "orange", "pear"] {
    print(data)
}

filter、map、reduceなどと組み合わせれば一貫性のある使い方ができますね。
次のようにしても同じ事ができるというのは秘密です。

taboo
["apple", "orange", "pear"].map { data in print(data) }
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3