将城市名称转换为Swift中的坐标

我看到了几个问题,但所有这些在Swift 2中都是旧的。我从Apple网站获得了这个函数来将城市名称转换为经度和纬度,但是我不确定函数将返回什么(因为返回语句之后没有任何东西),我应该通过什么。 请有人解释一下,或告诉我如何使用它请。

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) { placemarks, error in completion(placemarks?.first?.location?.coordinate, error) } } 

用法:

 getCoordinateFrom(address: "Rio de Janeiro, Brazil") { 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(coordinate) // CLLocationCoordinate2D(latitude: -22.910863800000001, longitude: -43.204543600000001) } } 

进行像获取城市坐标这样的asynchronous操作不能返回值作为函数结果。 您必须拨打电话,开始您的业务,并等待它打电话给您的完成处理程序。 那参数completionHandler是在上面的代码中。 一旦结果准备就绪,你将传入一个闭包(一段代码)。 你会这样使用它:

 getCoordinate(addressString: someString) { coordinate, error in if error != nil { //display error return } else { //at this point `coordinate ` contains a valid coordinate. //Put your code to do something with it here print("resulting coordinate = (\(coordinate.latitude),\(coordinate.longitude))") } } 

请注意,对于Swift 3,你会让你的函数抛出,而不是返回结果或错误。