ios - Swift 在闭包中传入变量

标签 ios arrays xcode swift closures

我需要为类编写一个函数,该函数使用闭包枚举类中的数组。从其他地方调用函数时,我需要在闭包中为我提供当前数组的索引。我知道如何编写函数,但如何在调用时使索引(和其他变量)可用?

附言

这应该类似于 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/

相关文章:

ios - 使用 Swift 对两个数组进行排序

arrays - 从随机数组中打印新的素数数组?

xcode - 如何在 Swift 中弯曲 UIViewController 的顶部?

iphone - Objective-C 中的协议(protocol)命名空间

ios - 同时下载和播放从多个 URL 拼凑而成的歌曲

ios - 找出superview的类名

iphone - iPhone 中的支付网关集成

ios - 在 SwiftUI App 中实现深色模式切换

C++ 数组初学者

ios - 将 UITextField 添加到代码作为 socket 时发出 Sigabrt 信号