简体   繁体   中英

Return Value from Function Swift

I know this is probably a simple queston, I would like to return the value of currentLocGeoPoint and return the array of Objects which is of type PFObject.

  1. Tried to save it as a global variable, but it doesn't work because it is asynchronous and doesn't take a value yet. Returns empty.
  2. Tried to return currentLocGeoPoint and changed Void in to PFGeoPoint in . Gives error: PFGeoPoint is not convertible to 'Void'

So I'm not sure how I can fetch the variable currentLocGeoPoint .

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
        if (error != nil) {
            println("Error:" + error.localizedDescription)
            //return
        }
        if placemarks.count > 0 {
            let pm = placemarks[0] as CLPlacemark
            self.displayLocationInfo(pm)
            currentLoc = manager.location 
            currentLocGeoPoint = PFGeoPoint(location:currentLoc)
            var query = PFQuery(className:"Bar") 
            query.whereKey("BarLocation", nearGeoPoint:currentLocGeoPoint, withinMiles:10) 
            query.limit = 500
            query.findObjectsInBackgroundWithBlock {
                (objects: [AnyObject]!, error: NSError!) -> Void in
                if objects != nil {  
                } else {
                    println("error: \(error)")
                }
            }
        } else {
            println("error: \(error)")
        }
    })
}

I don't understand the notion of "I want to return currentLocGeoPoint". Return it to what? You're in a CLLocationManagerDelegate method, so there's no one to return it to.

What you could do, though, is, when the request is done (ie within this closure), call some other function that needed the currentLocGeoPoint . Or you could update the UI to reflect the updated information (make sure to dispatch that update to the main thread, though). Or, if you have other view controllers or model objects that need to know about the new data, you might post a notification, letting them know that there is an updated currentLocGeoPoint . But within this method, there's no one to whom you would "return" the data.

You could assign it to a stored property of your class. Just use

self.<property> = currentLocGeoPoint

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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