gpt4 book ai didi

ios - 使用 MKDirections (Swift 4) 导出两点之间的行驶距离后,如何访问封闭之外的距离值?

转载 作者:行者123 更新时间:2023-11-30 11:07:29 24 4
gpt4 key购买 nike

我写了这样的东西来计算 2 点/位置之间的行驶距离。

方法实现:

第 1 类:

static func calculateDistance(_ location1 : CLLocationCoordinate2D, location2: CLLocationCoordinate2D, completion: @escaping (_ distance: CLLocationDistance?) -> ()) {

let start = MKMapItem(placemark: MKPlacemark(coordinate: location1))
let destination = MKMapItem(placemark: MKPlacemark(coordinate: location2))
let request = MKDirectionsRequest()
request.source = start
request.destination = destination
request.requestsAlternateRoutes = false
let direction = MKDirections(request: request)
var distanceInMiles: CLLocationDistance?

direction.calculate { (response, error) in
if let response = response, let route = response.routes.first {
distanceInMiles = route.distance * 0.000621371
completion(distanceInMiles)
}
}
}

使用问题

第 2 类:如何访问不同类别中的距离值?例如,我有一个参数化的 init,其中第三个参数 "dist" 的类型为 CLLocationDistance。我想要实现的是从 Class1 的 calculateDistance 方法访问距离值

let assigningDistValue = Class1(coordinate: location, secondParam: paramValue, dist:finalDistance!)

我几乎阅读了与此问题相关的所有建议解决方案,但没有任何帮助。

最佳答案

在闭包之后,您无法访问 finalDistance,因为代码按以下顺序运行:

var finalDistance: CLLocationDistance?
// 1:
let calculatedDistance = Class1.calculateDistance(location, location2: secondlocation) { (distance) in
// 3:
guard let distanceInMiles = distance else { return }
print("This is to print distance in miles", distanceInMiles)
finalDistance = calculatedDistance
}
// 2:
let assigningDistValue = Class1(coordinate: location, secondParam: paramValue, dist:finalDistance!)

只需将 let 行移至异步 Material 的末尾即可:

let calculatedDistance = Class1.calculateDistance(location, location2: secondlocation) { (distance) in
guard let distanceInMiles = distance else { return }
print("This is to print distance in miles", distanceInMiles)
finalDistance = calculatedDistance
// put it here
let assigningDistValue = Class1(coordinate: location, secondParam: paramValue, dist:finalDistance!) {
// and on we go...
}
}

或者,使用另一个完成 block ,就像您在显示的第一个代码中所做的那样。这在第一个代码中是正确的,但在第二个代码中,所有关于异步含义的知识似乎都被遗忘了。

关于ios - 使用 MKDirections (Swift 4) 导出两点之间的行驶距离后,如何访问封闭之外的距离值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52547089/

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