Swift 3.0:无法在当前上下文中推断闭包类型,PromiseKit

7
我在 Swift 3.0 中使用 PromiseKit 编写了以下代码。
func calculateTravelTime(from: CLLocation, to: CLLocation) -> Promise<Double> {
     Promise<Double> { completion, reject -> Void in
        let request = MKDirections.Request()
        request.transportType = .walking

        let fromPlacemark = MKPlacemark(coordinate: from.coordinate)
        let toPlacemark = MKPlacemark(coordinate: to.coordinate)

        let fromMapPoint = MKMapItem(placemark: fromPlacemark)
        let toMapPoint = MKMapItem(placemark: toPlacemark)

        request.source = fromMapPoint
        request.destination = toMapPoint
        request.requestsAlternateRoutes = false

        let directions = MKDirections(request: request)
        directions.calculate { response, error in
            if error != nil {
                reject(error!)
            } else {
                let time = (response?.routes.first?.expectedTravelTime ?? 0) / 60.0
               completion(time)
            }
        }

    }
} 

第二行出现以下错误:

“无法推断当前上下文中的闭包类型”

错误代码行:

Promise<Double> { completion, reject -> Void in

我无法确定为什么会出现这个错误。是否有任何熟悉Swift的专家可以帮助我解决这个问题。

谢谢!


1
Promise<Double> 看起来不像是一个函数。 - Jonathan
我没有使用 Promise Kit,只是快速浏览了文档,发现有 Promise<Void> 而没有 Promise<Double>。如果我错了,请忽略此信息。 - Prashant Tukadiya
嗯...你尝试过将除了 Promise<Double> { ... 以外的所有内容都注释掉,以便隔离错误吗? 此外,在文档中提到,你的类型应该是 ThenableCatchMixin:https://github.com/mxcl/PromiseKit/blob/master/Sources/Promise.swift#L8 也许是因为你的 Double 没有实现这些协议。 - rgkobashi
@rgkobashi 我尝试对所有内容进行注释。问题出在“completion, reject”上,如果我使用“_”,它可以正常工作。但是我需要完成和拒绝块。在Swift 2.0中它能够正常工作。 - PlusInfosys
哦,好的,那是一个进步。既然你提到它在Swift 2.0上运行良好,我想你更新了你的SDK,如果是这样的话,也许这个init方法(completion, reject -> Void作为参数)在新版本中不存在,我猜应该有一个相当的方法。我快速查看了文档,没有看到这种类型的init。 - rgkobashi
显示剩余8条评论
1个回答

14
在当前的PromiseKit版本中,这个 Promise<T> { fulfill, reject -> Void in } 被改为 Promise<T> { seal -> Void in } 因此,你的新实现将变成这样,
func calculateTravelTime(from: CLLocation, to: CLLocation) -> Promise<Double> {
     Promise<Double> { seal -> Void in
        let request = MKDirections.Request()
        request.transportType = .walking

        let fromPlacemark = MKPlacemark(coordinate: from.coordinate)
        let toPlacemark = MKPlacemark(coordinate: to.coordinate)

        let fromMapPoint = MKMapItem(placemark: fromPlacemark)
        let toMapPoint = MKMapItem(placemark: toPlacemark)

        request.source = fromMapPoint
        request.destination = toMapPoint
        request.requestsAlternateRoutes = false

        let directions = MKDirections(request: request)
        directions.calculate { response, error in
            if error != nil {
                seal.reject(error!)
            } else {
                let time = (response?.routes.first?.expectedTravelTime ?? 0) / 60.0
               seal.fulfill(time)
            }
        }

    }
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接