问题
I am trying to create function which can return CLLocation value?
As this is asynch method it gives value after some time and return get called before that. is there any way to return after getting lat, lon?
func setLocation(location: String) -> [String]{
var lat: CLLocationDegrees?
var lon: CLLocationDegrees?
geocoder.geocodeAddressString(location) { placemarks, error in
let placemark = placemarks?.first
lat = placemark?.location?.coordinate.latitude
lon = placemark?.location?.coordinate.longitude
print("Lat: \(lat), Lon: \(lon)") //here i get value
}
print("Lat: \(lat), Lon: \(lon)") //but here i get nil
return ["\(String(describing: lat))", "\(String(describing: lon))"]
}
回答1:
Use a completion
func setLocation(location: String,completion:@escaping(CLLocationCoordinate2D? -> ())) {
var lat: CLLocationDegrees?
var lon: CLLocationDegrees?
geocoder.geocodeAddressString(location) { placemarks, error in
let placemark = placemarks?.first
completion(placemark?.location?.coordinate)
}
}
setLocation(location: "") { (coor) in
print(coor.latitude)
}
来源:https://stackoverflow.com/questions/61728785/how-can-i-return-a-cllocation-value-in-swift