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

后端 未结 3 950
佛祖请我去吃肉
佛祖请我去吃肉 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:35

    I recently ran across a use case where using forEachwas preferable in a tangible way to for in. Let's say you want to remove all sublayers from a layer. A statement such as the below doesn't work as you need to unwrap the [CALayer]

    for layer in self.videoContainerView.layer.sublayers!
    

    If sublayers are nil, you will get a crash. This forces you to check to see if there are sublayers first. However, a forEach makes this much simpler as in the following:

    self.videoContainerView.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
    

提交回复
热议问题