我需要为类编写一个函数,该函数使用闭包枚举类中的数组。从其他地方调用函数时,我需要在闭包中为我提供当前数组的索引。我知道如何编写函数,但如何在调用时使索引(和其他变量)可用?
附言
这应该类似于 SpriteKit 中的 SKNode 如何通过子函数枚举,子节点可用于传入的闭包。
最佳答案
我不确定您想要实现什么目标。
也许像这样?
class MyClass {
var ary:[String] = ["foo","bar","baz"]
func enumerateArray(block: (String, Int, inout Bool) -> Void) {
var stop = false
for e in enumerate(ary) {
block(e.element, e.index, &stop)
if stop {
break
}
}
}
}
let obj = MyClass()
obj.enumerateArray { str, idx, stop in
println("\(idx): \(str)")
if str == "bar" {
stop = true
}
}
输出:
0: foo
1: bar
关于ios - Swift 在闭包中传入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27251229/