我怎么说在Swift中这个与闭包相关的代码的意思呢?

时间:2015-10-21 20:00:21

标签: ios swift asynchronous closures

我的第一个传递是JavaScript中的代码示例,它看起来应该可以工作,但仔细检查会有不同的行为。我的Swift代码目前有SwiftyJSON

    for(var index = 0; index < datesToLoad.count; index += 1) {
        var formattedDate = formatter.stringFromDate(datesToLoad[index]);
        if (presentLocation["days"][formattedDate] == nil) {
            loadDataFromURL(NSURL:"http://api.sunrise-sunset.org/json?formatted=0&lat=\(presentLocation.coordinate.latitude)&lon=\(presentLocation.coordinate.longitude)&date=\(formattedDate)&formatted=0", completion: {(data, error) -> Void in {
                if (var json = JSON(data:data)) {
                    presentLocation["days"][formattedDate]["sunrise"] = parser(json["results"]["sunrise"]);
                    presentLocation["days"][formattedDate]["sunset"] = parser(json["results"]["sunset"]);
                }
            }
        }
    }

现在我期望的是代码不能按预期工作。我想要实现的是,对于列表的每个formattedDate值,都会进行异步调用以从URL检索数据,并且每个API调用都将使用formattedDateloadDataFromURL()formattedDate值1}}打电话。我期望会发生的是循环将快速运行,产生一些异步请求,并且formattedDate将可用于定义它的最后一个值。我可以解决不知道如何在Swift中正确执行此操作,因为从API返回的数据提供了多个时间戳,但我想知道使用loadDataFromURL()的多个值的首选方法回调函数,查看调用其{{1}}函数时处于活动状态的版本。

我也可以通过完全展开(四元素)循环并为每个基于闭包的API调用使用单独的变量名来获得我想要的结果,但我真的更愿意知道什么是正确的交易方式有这种问题。

1 个答案:

答案 0 :(得分:1)

每次通过for循环都会创建一个新的formattedDate变量,该变量独立于在任何其他传递中创建的formattedDate变量。

因此你的循环应该按照你的意图行事。

游乐场演示:

import XCPlayground
import UIKit

var blocks: [()->Void] = []

for i in 0..<5 {
    var s = "\(i)"
    blocks.append( { print(s) } )
}

print("calling blocks")

for block in blocks {
    block()
}

输出:

calling blocks
0
1
2
3
4