ios - 上下文闭包类型...需要 2 个参数,但在闭包体中使用了 3 个
问题描述
亲爱的高级程序员,
您能否协助一个相当新的程序员编辑此代码。好像新版本的Xcode不支持下面的代码并显示错误:
**"Contextual closure type '(Directions.Session, Result<RouteResponse, DirectionsError>) -> Void' (aka '((options: DirectionsOptions, credentials: DirectionsCredentials), Result<RouteResponse, DirectionsError>) -> ()') expects 2 arguments, but 3 were used in closure body"**
代码直接从 mapbox 文档网站复制而来。任何形式的帮助将不胜感激。提前致谢。
func getRoute(from origin: CLLocationCoordinate2D,
to destination: MGLPointFeature) -> [CLLocationCoordinate2D]{
var routeCoordinates : [CLLocationCoordinate2D] = []
let originWaypoint = Waypoint(coordinate: origin)
let destinationWaypoint = Waypoint(coordinate: destination.coordinate)
let options = RouteOptions(waypoints: [originWaypoint, destinationWaypoint], profileIdentifier: .automobileAvoidingTraffic)
_ = Directions.shared.calculate(options) { (waypoints, routes, error) in
guard error == nil else {
print("Error calculating directions: \(error!)")
return
}
guard let route = routes?.first else { return }
routeCoordinates = route.coordinates!
self.featuresWithRoute[self.getKeyForFeature(feature: destination)] = (destination, routeCoordinates)
}
return routeCoordinates
}
解决方案
请开发人员学习阅读错误消息和/或文档。
该错误清楚地表明闭包的类型是(Directions.Session, Result<RouteResponse, DirectionsError>) -> Void
(2个参数),它代表一个会话(一个元组)和一个Result
包含响应和潜在错误的自定义类型。
你必须写一些像
_ = Directions.shared.calculate(options) { (session, result) in
switch result {
case .failure(let error): print(error)
case .success(let response):
guard let route = response.routes?.first else { return }
routeCoordinates = route.coordinates!
self.featuresWithRoute[self.getKeyForFeature(feature: destination)] = (destination, routeCoordinates)
}
}
除了这个问题之外,不可能从异步任务中返回某些东西,例如,您必须添加一个完成处理程序
func getRoute(from origin: CLLocationCoordinate2D,
to destination: MGLPointFeature,
completion: @escaping ([CLLocationCoordinate2D]) -> Void) {
并在闭包内的案例completion(route.coordinates!)
结束时调用success
推荐阅读
- python - 数组中大数的索引
- git - 为什么'git push'(没有-f)会覆盖远程历史?[GitHub]
- node.js - 来自后端的输入验证显示在控制台上,但不显示在前端 React、nodejs 引导程序上
- c# - C# 扩展列表
对于 DateTime 属性之一 - python - 如何在 aws lambda 中设置 git config
- r - R 排除统计数据中的异常值
- javascript - 获取源时区的小时数
- database - 如何在 MS Access 中打开导航表单到特定选项卡
- css - Firefox 和 Chrome 上的 CSS 转换倾斜故障
- java - 外部 jar 最终名称