在swift中从闭包获取数据 [英] Getting data out of a closure in swift

查看:148
本文介绍了在swift中从闭包获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在解析中提取了一个查询,并获取了一个GeoPoint坐标数组。这是在一个闭合内。我只能访问闭包内的数组值。我需要能够使用这些值,所以他们可以用作地图上的注释,但我不能得到他们。可以有人告诉我如何从闭包中获取数组值。

I have made a query in parse and fetched an array of GeoPoint coordinates. This was done inside a closure. I can only access the array values inside that closure. I need to be able to use those value so they can be used as annotations on a map but I can't get to them. Can somebody tell me how to get the array values out of the closure.

代码:

var user = PFUser.currentUser()
user["location"] = geopoint

var query = PFUser.query()
query.whereKey("location", nearGeoPoint:geopoint)
query.limit = 10
query.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]!, error: NSError!) -> Void in

    for object in objects {

        var user:PFUser = object as PFUser
        var otherUsersCoord = [PFGeoPoint]()
        otherUsersCoord.append(user["location"] as PFGeoPoint)

        println("The other users coords are: \(otherUsersCoord)")
    }

})}


推荐答案

声明 otherUsersCoord 闭包表达式,而不是里面。当它被分配到闭包中时,该变化将反映在闭包外部的变量中。这被称为捕获 otherUsersCoord 。捕获外部上下文是什么使得闭包不仅仅是函数。

Declare otherUsersCoord as a var outside the closure expression, rather than inside it. When it is assigned to within the closure, that change will be reflected in the variable outside the closure. This is known as "capturing" otherUsersCoord. Capturing external context is what makes closures more than just functions.

但是,请注意,您仍然需要等待闭包实际运行之前,变量将具有您决定的值。它不会立即同步可用。此外,捕获外部变量保持它们活着,并且偶尔可能导致循环引用和类似的问题(这是为什么有时当你引用成员变量或函数,你得到关于捕获自我的警告)。

Beware though, you still need to wait for the closure to actually run before the variable will have the value you decide. It won’t be instantly synchronously available. Also, capturing external variables keeps them alive and can occasionally result in cyclic references and similar problems (this is why sometimes when you refer to a member variable or function you get a warning about "capturing self").

这篇关于在swift中从闭包获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆