【问题标题】:Swift - type of expression is ambigious without more contextSwift - 表达式的类型在没有更多上下文的情况下是模棱两可的
【发布时间】:2015-11-20 13:48:16
【问题描述】:

我正在尝试在 Swift 中为 Alamofire 做一个扩展,并拥有以下代码:

import Foundation
import Alamofire

protocol JsonResponse
{
    init?(json : NSObject)
}

extension Request
{
    func responseObject<T : JsonResponse, Error: ErrorType>(completionHandler : Result<T,Error> -> Void) -> Self
    {
        return responseJSON(completionHandler: {r  in
            let result = r.result
            guard result.isSuccess else {
                completionHandler(.Failure(result.error!))
                return
            }
            let obj : T? = T(json : result.value as! NSObject)
            let success : Result<T,Error> = .Success(obj!)
            completionHandler(success)
        })

    }
}

这给了我编译器错误:

错误:(21, 36) 表达式类型不明确,没有更多上下文

有趣的是,当我注释掉这一行时,它会编译:

// completionHandler(.Failure(result.error!))

如何为 Swift 提供足够的类型信息来完成这项工作?

【问题讨论】:

    标签: xcode swift swift2 swift2.1


    【解决方案1】:

    问题在于不知道 Result 类型 (.Failure(result.error!)) 的类型。作为失败案例,没有什么可以告诉编译器 T 将是什么。

    你可以完整写出来Result&lt;T,Error&gt;.Failure(result.error!)

    【讨论】:

    • 我有点惊讶,作为完成处理程序的参数没有提供足够的类型上下文。
    【解决方案2】:

    我用这个编译它:

    completionHandler(Result<T,Error>.Failure(result.error! as! Error))
    

    一个问题是类型推断,另一个是 result.error 是一个可选的 NSError。我不知道 NSError 是否可以转换为 ErrorType tho..

    【讨论】:

      【解决方案3】:
      extension Request
      {
          // this function declares return type Self (aka Request)
          func responseObject<T : JsonResponse, Error: ErrorType>(completionHandler : Result<T,Error> -> Void) -> Self
          {
              // here you return ... I don't know, but the type
              // is return type of the function responseJSON,
              // probably Void too
              return responseJSON(completionHandler: {r  in
                  let result = r.result
                  guard result.isSuccess else {
                      completionHandler(.Failure(result.error!))
                      // here you return Void
                      return
                  }
                  let obj : T? = T(json : result.value as! NSObject)
                  let success : Result<T,Error> = .Success(obj!)
                  completionHandler(success)
              })
      
          }
      }
      

      我猜你需要类似的东西

      func responseObject<T : JsonResponse, Error: ErrorType>(completionHandler : Result<T,Error> -> Void) -> Void
      

      【讨论】:

        猜你喜欢
        • 2017-04-17
        • 1970-01-01
        • 1970-01-01
        • 2017-09-09
        • 1970-01-01
        • 2017-11-23
        • 2021-08-05
        • 1970-01-01
        相关资源
        最近更新 更多