首页 > 解决方案 > 上下文闭包类型...需要 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
}

标签: iosmapboxmapbox-ios

解决方案


开发人员学习阅读错误消息和/或文档

该错误清楚地表明闭包的类型是(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


推荐阅读