Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

ios - Getting data out of a closure in swift

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.

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

})}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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”).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...