如何快速在for循环中使用闭包? [英] How to use closures in a for loop in swift?

查看:160
本文介绍了如何快速在for循环中使用闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列快速的按钮.每个按钮都有一个闭合.我试图在for循环中使用i作为每个闭包中的值.

I have an array of buttons in swift. Each button has a closure. I'm trying to use i in the for loop as a value in each closure.

 for(var i = 0; i < 30; i++){
            chapterOnePanel.chapters[i].onClickListener = {
                (x:Float32, y:Float32) in
                let r = i + 1;
                self.ChapterLoad = "1";
                self.LevelLoad = String(r);
                self.loadLevel = true;
            }
        }

如您所见,我在循环中使用 i i + 1 存储在 r 中,然后存储 r LevelLoad 变量中.但是,这不起作用,应用程序崩溃且LevelLoad标记为nil.我知道在Java中,必须将 r 变量声明为最终变量才能起作用.在Swift中有没有办法做到这一点?

As you can see I'm using i in the loop to store i+1 in r and then store r in the LevelLoad variable. This doesn't work however, app crashes and LevelLoad is marked as nil. I know in Java you have to declare the r variable as final for it to work. Is there a way to do this in Swift?

这是下面GoZoner提供的答案.

Here is the answer as provided by GoZoner below.

     for(var i = 0; i < 30; i++){
              let r = i + 1;                    
              chapterOnePanel.chapters[i].onClickListener = {
                        (x:Float32, y:Float32) in

                        self.ChapterLoad = "1";
                        self.LevelLoad = String(r);
                        self.loadLevel = true;
                    }
                }

推荐答案

这是一个错误:

var data : [(Int) -> ()] = []

for (var i = 0; i < 5; i++) {
  data.append { (j:Int) in
    println (j + i)
  }
}

 9> data[0](10)  
15 // should be 10

变量i不能在闭包的主体中进行修改,因此必须复制"(请参见"捕获值')创建闭包时的值.相反,显然,编译器认为i是可修改的,尽管它在闭包之外,并且错误地得出结论认为需要引用".

The variable i IS NOT modified in the body of the closure, it thus MUST BE 'copied' (see 'Capturing Values') when the closure is created. Instead, apparently, the compiler sees that i is modfiable, albeit outside of the closure, and incorrectly concludes that a 'reference' is needed.

要解决此问题,请将引用移至闭包外部错误捕获的i:

To work around, move reference to the incorrectly captured i, outside of the closure:

Welcome to Swift version 1.2. Type :help for assistance.
  1> var data : [(Int) -> ()] = [] 
  2.  
  3. for (var i = 0; i < 5; i++) { 
  4.   let r = i
  5.   data.append { (j:Int) in 
  6.     println (j + r)
  7.   } 
  8. } 
data: [Int -> ()] = 5 values {
  [0] = ($__lldb_expr2`partial apply forwarder for reabstraction thunk helper from @callee_owned (@unowned Swift.Int) -> (@unowned ()) to @callee_owned (@in Swift.Int) -> (@out ()) at repl1.swift)
  ...
  [4] = ($__lldb_expr2`partial apply forwarder for reabstraction thunk helper from @callee_owned (@unowned Swift.Int) -> (@unowned ()) to @callee_owned (@in Swift.Int) -> (@out ()) at repl1.swift)
}
  9> data[0](10)
10
 10> data[4](10)
14

这篇关于如何快速在for循环中使用闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆