var arrayLength:Int = 0 // is equal to 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let urlPath = "http://example.com/json"

    let url = NSURL(string: urlPath)!
    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithURL(url, completionHandler: {
        data, response, error in

        if (error? != nil) {
            println(error)
        } else {
            var jsonResponse: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)

            let json = JSON(jsonResponse!)
            self.arrayLength = json["dump"].array?.count as Int!
            println("Second: \(self.arrayLength)") // is equal to 3

            for postIndex in 0...self.arrayLength-1 {
                println(json["dump"][postIndex]["title"])
            }
        }

    })
    task.resume()

    println(arrayLength) // is equal to 0 again

我设置了
var arrayLength:Int = 0

在代码的开头。稍后在viewdidload()中,我将其更改为3。当我调用它时,在任务块之外它再次等于0。这里的问题是什么?我做错了什么?

最佳答案

是的,您在闭包中更改了您的arrayLengthvar。你现在面临的问题就是线程如何工作的正常方式。
viewDidLoad开始时,你就在主线程上了
let task = session.dataTaskWithURL(url, completionHandler: { ...定义了一个尚未执行的新任务
task.resume()在另一个线程上启动此任务。这需要一些时间来完成。完成后,您的arrayLength将被更改
立即在主线程上询问您的arrayLength
在这里:

     println(arrayLength) // is equal to 0 again

这不是说arraylength再次等于0,您没有给任务足够的时间来执行和更改该值。
编辑:如果关闭完成后需要检查阵列长度…
只需创建一个函数并在闭包内调用它最后一件事。这样地:
override func viewDidLoad() {
   ...

    let task = session.dataTaskWithURL(url, completionHandler: {
        data, response, error in

        if (error? != nil) {
            println(error)
        } else {
            var jsonResponse: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)

            let json = JSON(jsonResponse!)
            self.arrayLength = json["dump"].array?.count as Int!
            println("Second: \(self.arrayLength)") // is equal to 3

            for postIndex in 0...self.arrayLength-1 {
                println(json["dump"][postIndex]["title"])
            }

            functionToDoSomethingAtTheEndOfTheClosure();
        }

    })
    task.resume()
}

func functionToDoSomethingAtTheEndOfTheClosure() {
  // this is going to be executed at the end of the closure's code
}

关于swift - 变量不会在闭包之外变化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29484783/

10-09 02:21