我几乎没有看到关于SO的问题,但所有问题在Swift 2中都是古老的。
我从Apple网站上获得了此功能,可以将城市名称转换为纬度和经度,但是我不确定该功能将返回什么(因为return语句后没有任何内容)以及应该传递什么。有人可以解释一下吗,或者告诉我如何使用它。

func getCoordinate( addressString : String,
        completionHandler: @escaping(CLLocationCoordinate2D, NSError?) -> Void ) {
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(addressString) { (placemarks, error) in
        if error == nil {
            if let placemark = placemarks?[0] {
                let location = placemark.location!

                completionHandler(location.coordinate, nil)
                return
            }
        }

        completionHandler(kCLLocationCoordinate2DInvalid, error as NSError?)
    }
}

最佳答案

您可以按照以下步骤进行操作:

import CoreLocation

func getCoordinateFrom(address: String, completion: @escaping(_ coordinate: CLLocationCoordinate2D?, _ error: Error?) -> () ) {
    CLGeocoder().geocodeAddressString(address) { completion($0?.first?.location?.coordinate, $1) }
}


用法:

let address = "Rio de Janeiro, Brazil"

getCoordinateFrom(address: address) { coordinate, error in
    guard let coordinate = coordinate, error == nil else { return }
    // don't forget to update the UI from the main thread
    DispatchQueue.main.async {
        print(address, "Location:", coordinate) // Rio de Janeiro, Brazil Location: CLLocationCoordinate2D(latitude: -22.9108638, longitude: -43.2045436)
    }

}

10-07 22:51