gpt4 book ai didi

swift - 何时使用 forEach(_ :) instead of for in?

转载 作者:IT王子 更新时间:2023-10-29 05:07:46 25 4
gpt4 key购买 nike

Array 中所述和 Dictionary forEach(_:) 实例方法:

Calls the given closure on each element in the sequence in the same order as a for-in loop.

尽管如此,改编自 Sequence Overview :

A sequence is a list of values that you can step through one at a time. The most common way to iterate over the elements of a sequence is to use a for-in loop.

通过 forEach(_:)for in 暗示迭代序列:

let closedRange = 1...3

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

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

或(数组):

let array = [1, 2, 3]

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

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

会给出相同的输出。

为什么 forEach(_:) 甚至存在?即使用它代替 for in 循环有什么好处?从性能的角度来看,它们是否相同?

作为一种假设,它可能是一种语法糖,尤其是在使用函数式编程时。

最佳答案

forEach 没有性能优势。事实上,if you look at the source codeforEach 函数实际上只是执行for-in。对于发布版本,此函数的性能开销比简单地使用 for-in 自己是无关紧要的,但对于调试版本,它会导致可观察到的性能影响。

forEach 的主要优点是在进行函数式编程时实现的,您可以将它添加到函数调用链中,而不必将先前的结果保存到您希望的单独变量中如果您使用 for-in 语法,则需要。所以,而不是:

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

for object in objects {
...
}

您可以改用函数式编程模式:

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

结果是功能代码更简洁,语法噪音更少。

FWIW,Array 的文档, Dictionary , 和 Sequence所有这些都提醒我们 forEach 引入的限制,即:

  1. You cannot use a break or continue statement to exit the current call of the body closure or skip subsequent calls.

  2. Using the return statement in the body closure will exit only from the current call to body, not from any outer scope, and won't skip subsequent calls.

关于swift - 何时使用 forEach(_ :) instead of for in?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45333177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com