简体   繁体   English

快速从闭包中获取数据

[英]Getting data out of a closure in swift

I have made a query in parse and fetched an array of GeoPoint coordinates. 我在解析时发出了一个查询并获取了一个GeoPoint坐标数组。 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. 有人可以告诉我如何从闭包中获取数组值。

code: 码:

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

})}

Declare otherUsersCoord as a var outside the closure expression, rather than inside it. otherUsersCoord声明为闭包表达式之外的var,而不是在其中。 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 . 这被称为“捕获” 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”). 此外,捕获外部变量会使它们保持活动状态并且偶尔会导致循环引用和类似问题(这就是为什么有时当您引用成员变量或函数时会收到关于“捕获自我”的警告)。

You would usually do something like: 你通常会这样做:

If the closure is in a method on some helper class, pass it a completion block parameter that takes the array as a parameter. 如果闭包在一个辅助类的方法中,则传递一个以数组作为参数的完成块参数。 When the completion block is called, store the array as an instance variable (and trigger an update to your UI) or create the annotations and set them onto your map view (which would be an instance variable). 调用完成块时,将数组存储为实例变量(并触发对UI的更新)或创建注释并将其设置到地图视图(这将是实例变量)。

If the closure is in a method on your class that owns the map view then you can skip the completion block part and just deal with the array directly to update your instance variable / map. 如果闭包位于拥有地图视图的类的方法中,则可以跳过完成块部分,直接处理数组以更新实例变量/ map。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM