import Foundation
import CoreLocation

class Converters  {
private var coordinate: String = ""
let geocoder = CLGeocoder()
func CityToCoordinate(city: String) ->String {
    geocoder.geocodeAddressString(city, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
        if((error) != nil){
            print("Error", error)
        }
        if let placemark = placemarks?.first {
            let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
            self.coordinate = "\(coordinates.latitude),\(coordinates.longitude)"
            print(self.coordinate) //Here, I get the value: 47.7845996,19.1310416
        }
    })
    print(coordinate) //Has no value, but I need the same: "47.7845996,19.1310416"
    return coordinate // Don't return anything, I set in geocoder
}


}

Image
有什么解决办法吗?我想从completionHandler事件中获取字符串,需要返回坐标。

最佳答案

将完成处理程序添加到CityToCoordinate签名:

completion: (string: String)->()

在有数据的地方使用。
这样地:
class Converters  {
    private var coordinatese: String = ""
    let geocoder = CLGeocoder()

    func CityToCoordinate(city: String, completion: (string: String)->()) {
        geocoder.geocodeAddressString(city, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
            if((error) != nil){
                print("Error", error)
            }
            if let placemark = placemarks?.first {
                let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
                self.coordinatese = "\(coordinates.latitude),\(coordinates.longitude)"

                completion(string: self.coordinatese)
            }
        })
    }
}

并用尾随闭包调用它:
let conv = Converters()
conv.CityToCoordinate("Paris") { (string) in
    print(string)  // 48.8567879,2.3510768
}

09-11 22:59