When to use forEach(_:) instead of for in?

后端 未结 3 957
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-09 01:12

As documented in both Array and Dictionary forEach(_:) Instance methods:

Calls the given closure on each element in the sequence<

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 01:37

    They are more or less interchangeable, but there are two important differences.

    1. break/continue only work in a for .. in
    2. return in forEach will exit the closure, but will not halt the iteration.

    The reason for this is that for .. in is a special form in the language (which allows break and continue to work as you expect). It is something that you can't implement in an identical way using the language itself.

    However, forEach is not a special form and can be re-implemented identically by writing it as a function.

    extension Sequence {
        func myOwnForEach(_ body: (Self.Element) throws -> Void) rethrows {
            let it = Self.makeIterator()
            while let item = it.next() {
                body(item)
            }
        }
    }
    

提交回复
热议问题