按值传递Int到关闭

时间:2015-04-10 12:28:27

标签: swift for-loop closures

我有这段代码:

for var i = 0; i < self.blockViews.count; i++ {
    UIView.animateWithDuration(0.2, animations: {
        // Some animation
        }, completion: {
            completion in
            // i is always blockViews.count as the for loop exits before completion closure is called
            if i == 0 {
                // Some completion handling
            }
    })
}

我试图在我的封闭内使用i;有没有办法做到这一点,除了将其分配给let,然后使用它(按值传递)?

for var i = 0; i < self.blockViews.count; i++ {
    let copyOfI = i
    UIView.animateWithDuration(0.2, animations: {
        // Some animation
        }, completion: {
            completion in
            if copyOfI == 0 {
                // This works
            }
    })
}

2 个答案:

答案 0 :(得分:3)

实际上有一种实现这一目标的方法,它被称为捕获列表:您只需将要捕获的变量列为以逗号分隔的列表包含在其中方括号 - 在您的情况下,它只是[i]

for var i = 0; i < self.blockViews.count; i++ {
    UIView.animateWithDuration(0.2, animations: {
        // Some animation
        }, completion: {
            [i] completion in
         // ^^^ capture list is here
            // i is always blockViews.count as the for loop exits before completion closure is called
            if i == 0 {
                // Some completion handling
            }
            println(i)
    })
}

参考:Closure Expression

旧答案

您可以将循环代码括在闭包中,并将索引作为闭包参数传​​递:

for var i = 0; i < self.blockViews.count; i++ {
    { (index) in
        UIView.animateWithDuration(0.2, animations: {
            // Some animation
            }, completion: {
                completion in
                // i is always blockViews.count as the for loop exits before completion closure is called
                if index == 0 {
                    // Some completion handling
                }
        })
    }(i)
}

答案 1 :(得分:1)

您必须使用let创建副本(就像您在问题中所做的那样)或通过闭包的参数将其传递到闭包中。

看到你正在使用UIView.animateWithDuration闭包,最好的办法是将它分配给闭包内的let变量。