swift - Swift 闭包问题

标签 swift parse-platform closures

我在从闭包中检索数据时遇到问题。我正在调用名为 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
    }
}

问题

如何从闭包中获取值?

最佳答案

那是因为 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)
    }

}

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

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)
    }

}

关于swift - Swift 闭包问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32483217/

相关文章:

python - 多次调用后更改内部函数中的非局部变量的结果

ios - 我没有写入 iCloud 文件夹的权限

ios - 使用 RxSwift 在 UIWebView 中捕获点击的链接

ios - “AnyObject”与 '[NSObject : AnyObject]' 不同

python - 如何使导入/关闭从 IPython 的嵌入工作?

swift - 使用 Swift : body of closure not executed 进行单元测试

arrays - 对数组应用范围过滤器

swift - UIImage从对象c到swift并且图像大小不好

ios - 解析/PFQueryTableView : Append extra text to an object in parse

javascript - undefined 不是一个函数(在 React Native 中评估 this.function()