gpt4 book ai didi

Swift 从 completionHandler 获取字符串

转载 作者:行者123 更新时间:2023-11-28 06:47:20 25 4
gpt4 key购买 nike

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
}

关于Swift 从 completionHandler 获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35942394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com