LoginSignup
1
1

More than 5 years have passed since last update.

Swift の Array に each を実装する

Posted at

Swift の Array に each を実装する方法、これでいいのかな?
配列の中身が AnyObject だった時も、受け取るブロックで型指定してたら、
キャストして渡すようにしたかったんだけど、Generics の使い方がいまいちかも。。

extension Array {

    func each(block: (T) -> ()) {
        for item in self {
            block(item)
        }
    }

    func each<U>(block: (U) -> ()) {
        for item in self {
            block(item as! U)
        }
    }

    func eachWithIndex(block: (T, Int) -> ()) {
        for (i, item) in enumerate(self) {
            block(item, i)
        }
    }

    func eachWithIndex<U>(block: (U, Int) -> ()) {
        for (i, item) in enumerate(self) {
            block(item as! U, i)
        }
    }
}

[1, 2, 3].each { (n: Int) in println(n) }
[1, 2, 3].each { println($0) }
[1, 2, 3].eachWithIndex { (n: Int, i: Int) in println("index \(i), n \(n)") }
[1, 2, 3].eachWithIndex { println("index \($1), n \($0)") }
1
1
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
1
1