How can I return a CLLocation value in swift? [duplicate]

佐手、 提交于 2020-05-14 14:13:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!