gpt4 book ai didi

swift - Swift 的 for-in 循环是如何工作的?

转载 作者:搜寻专家 更新时间:2023-10-31 22:09:12 24 4
gpt4 key购买 nike

使用 Java 的 Stream API 可以使用功能 internal iteration在集合上,就像

collection.forEach(out::println)

Swift 是否遵循 for-each 循环结构...

for i in names {
println(i)
}

...仅仅是内部(功能)迭代的语法糖,也可以解释为以下命令式 for 循环?

for var i = 0; i < names.count; i++ {
println(names[i])
}

最佳答案

language reference声明对于 for - in循环,

The generate() method is called on the collection expression to obtain a value of a generator type—that is, a type that conforms to the Generator protocol. The program begins executing a loop by calling the next() method on the stream. If the value returned is not None, it is assigned to the item pattern, the program executes the statements, and then continues execution at the beginning of the loop. Otherwise, the program does not perform assignment or execute the statements, and it is finished executing the for-in statement.

所以,我们可以这样说

for i in names {
println(i)
}

大致相当于

var g = names.generate()  // "var" because next() is a mutating function
while let i = g.next() { // "let" pattern because next() returns an optional
println(i)
}

至于函数迭代,嗯,我们有 SequenceType 的 func map<T>(_ transform: (Element) -> T) -> [T] .

关于swift - Swift 的 for-in 循环是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24445481/

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