本文介绍了什么时候使用forEach(_ :)而不是in?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如和 forEach(_:)实例方法:
$ b

然而,改编自:


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

Nevertheless, adapted from Sequence Overview:

Implying that iterating sequence by forEach(_:) or for in:

let closedRange = 1...3

for element in closedRange { print(element) } // 1 2 3

closedRange.forEach { print($0) } // 1 2 3

Or (Array):

let array = [1, 2, 3]

for element in array { print(element) } // 1 2 3

array.forEach { print($0) } // 1 2 3

Would gives the same output.

Why forEach(_:) even exist? i.e what is the benefit of using it instead of the for in loop? would they be the same from performance point view?

As an assumption, it could be a syntactic sugar especially when working with functional programming.

解决方案

There is no performance benefit offered by forEach. In fact, if you look at the source code, the forEach function actually simply performing for-in. For release builds, the performance overhead of this function over simply using for-in yourself is immaterial, though for debug builds, it results in an observable performance impact.

The main advantage of forEach is realized when you are doing functional programming, you can add it to a chain of functional calls, without having to save the prior result into a separate variable that you'd need if you used for-in syntax. So, instead of:

let objects = array.map { ... }
    .filter { ... }

for object in objects {
    ...
}

You can instead stay within functional programming patterns:

array.map { ... }
    .filter { ... }
    .forEach { ... }

The result is functional code that is more concise with less syntactic noise.

FWIW, the documentation for Array, Dictionary, and Sequence all remind us of the limitations introduced by forEach, namely:

这篇关于什么时候使用forEach(_ :)而不是in?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:36