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