如何快速返回CLLocation值? [重复]

我正在尝试创建可以返回CLLocation值的函数?

由于这是一个异步方法,因此它会在一段时间后赋值,并在此之前返回get。 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))"]

        }
评论
  • 喔不昰玩具
    喔不昰玩具 回复

    geocodeAddressString方法是一个异步调用。因此,该方法将在该方法实际收到响应之前返回。

    In this type of scenarios you need to use closure to pass the result.

    func setLocation(location: String, completion: ((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
            completion("\(String(describing: lat))", "\(String(describing: lon))")
        }    
    }
    

    这样称呼,

    setLocation(location: "") { (str) in
        print(str)
    }
    
  • 情癌晚期
    情癌晚期 回复

    使用补全

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