Swift Closures问题

Mar*_*oon 0 closures parse-platform swift

我在从闭包中检索数据时遇到问题.我正在调用函数getWallImages,它应该返回一个数组.我可以从闭包内打印数组的内容,但在它之外,数组是空的.

import Foundation
import Parse

class WallPostQuery {

    var result = [WallPost]()

    func getWallImages() -> [WallPost] { 
        let query = WallPost.query()!

        query.findObjectsInBackgroundWithBlock { objects, error in    
            if error == nil {     
                if let objects = objects as? [WallPost] {
                    self.result = objects
                    //This line will print the three PFObjects I have
                    println(self.result)
                }
            }
        }

        //this line prints [] ...empty array?
        println(result)
        return self.result
    }
}
Run Code Online (Sandbox Code Playgroud)

如何从闭包中获取值?

Swi*_*y89 5

那是因为println(result)之前执行了self.results = objects.闭包是异步执行的,因此它会在之后执行.尝试创建一个使用可以从闭包中调用的结果的函数:

var result = [WallPost]()
    func getWallImages() {

        let query = WallPost.query()!

        query.findObjectsInBackgroundWithBlock { objects, error in

            if error == nil {

                if let objects = objects as? [WallPost] {
                    self.result = objects
                    //This line will print the three PFObjects I have
                    println(self.result)
                    self.useResults(self.result)
                }
            }
        } 
    }

    func useResults(wallPosts: [WallPost]) {
        println(wallPosts)
    }

}
Run Code Online (Sandbox Code Playgroud)

您的问题的另一个解决方案,以便您可以从该函数返回它是创建自己的闭包:

var result = [WallPost]()
    func getWallImages(completion: (wallPosts: [WallPost]?) -> ()) {

        let query = WallPost.query()!

        query.findObjectsInBackgroundWithBlock { objects, error in

            if error == nil {

                if let objects = objects as? [WallPost] {
                    self.result = objects
                    //This line will print the three PFObjects I have
                    println(self.result)
                    completion(wallPosts: self.result)
                } else {
                    completion(wallPosts: nil)
                }
            } else {
                completion(wallPosts: nil)
            }
        } 
    }

    func useResults(wallPosts: [WallPost]) {
        println(wallPosts)
    }

}
Run Code Online (Sandbox Code Playgroud)