最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift中result使用出错:Cannot convert call result type Result to expected type Void aka

iOS crifan 1623浏览 0评论

对于Alamofire的result:

<code>public enum Result&lt;Value, Error : ErrorType&gt; {
    case Success(Value)
    case Failure(Error)
    /// Returns `true` if the result is a success, `false` otherwise.
    public var isSuccess: Bool { get }
    /// Returns `true` if the result is a failure, `false` otherwise.
    public var isFailure: Bool { get }
    /// Returns the associated value if the result is a success, `nil` otherwise.
    public var value: Value? { get }
    /// Returns the associated error value if the result is a failure, `nil` otherwise.
    public var error: Error? { get }
}
</code>

现在对于函数:

<code>   func getUrlRespJson_async(httpMethod:Alamofire.Method, url:String, parameters: [String : AnyObject]? = nil, headers: [String : String]? = nil ) -&gt; Alamofire.Result&lt;JSON, NSError&gt; {
</code>

中,最后想要去返回对应的result:

写成:

<code>func getUrlRespJson_async(httpMethod:Alamofire.Method, url:String, parameters: [String : AnyObject]? = nil, headers: [String : String]? = nil ) -&gt; Alamofire.Result&lt;JSON, NSError&gt; {

        Alamofire
            .request(
            httpMethod,
            url,
            parameters: parameters,
            encoding: ParameterEncoding.JSON,
            headers: currentHeaders)

            .responseJSON(completionHandler: { response in

            switch response.result {
            case .Success(let value):

                let valueJson = JSON(value)

                if let code = valueJson["code"].int {
                    if code == 200 {
                        if let dataDict = valueJson["data"].dictionary {
                            //maybe empty/int/json/...

                            let dataJson = JSON(dataDict)
                            gLog.verbose("dataJson=\(dataJson)")

                            return Alamofire.Result.Success(dataJson)
                        }
</code>

结果出错:

 Cannot convert call result type ‘Result<_, _>’ to expected type ‘Void’ (aka ‘()’)

 Cannot convert call result type ‘Result<_, _>’ to expected type ‘Void’ (aka ‘()’)

Cannot convert call result type Result<_, _> to expected type

参考:

A Swifter Way Of Handling Errors | Jens Ravens

要不去,自己手动创建一个:

结果用:

<code>enum HttpResult&lt;T&gt; {
    case Success(T)
    case Error(NSError)
}

    func getUrlRespJson_async(httpMethod:Alamofire.Method, url:String, parameters: [String : AnyObject]? = nil, headers: [String : String]? = nil ) -&gt; HttpResult&lt;JSON&gt; {

                            //let dataJson = JSON(dataDict)
                            let dataJson:JSON = JSON(dataDict)
                            gLog.verbose("dataJson=\(dataJson)")

                            return HttpResult.Success(dataJson)
</code>

竟然还是同样错误:

 Cannot convert call result type ‘HttpResult<_>’ to expected type ‘Void’ (aka ‘()’)

swift generic type

swift generic type result

The Swift Programming Language (Swift 2.2): Generics

Generics in Swift, Part 2 · Episteme and Techne

Swift Generics

Introduction to Swift Generics

Swift Tutorial: Introduction to Generics

后来发现是自己的函数写错了:

是写在了Alamofire的response的completionHandler部分

-》其是属于返回为空的

-》可以通过定义看出:

<code>    public func responseJSON(queue queue: dispatch_queue_t? = default, options: NSJSONReadingOptions = default, completionHandler: Alamofire.Response&lt;AnyObject, NSError&gt; -&gt; Void) -&gt; Self
</code>

-》completionHandler是个闭包的代码段

得到的值是:

Alamofire.Response<AnyObject, NSError>

此处拿到的是response那个值

对应的返回值是:Void,即无返回值

-》所以此处返回了Alamofire.Result的变量,才出错的

—》对于:

<code>func getUrlRespJson_async(httpMethod:Alamofire.Method, url:String, parameters: [String : AnyObject]? = nil, headers: [String : String]? = nil ) -&gt; Alamofire.Result&lt;JSON, NSError&gt; {

        Alamofire
            .request(
            httpMethod,
            url,
            parameters: parameters,
            encoding: ParameterEncoding.JSON,
            headers: currentHeaders)

            .responseJSON(completionHandler: { response in
。。。
                        return Alamofire.Result.Success(dataJson)
</code>

所以才出错的

应该改为:

<code>func getUrlRespJson_async(httpMethod:Alamofire.Method, url:String, parameters: [String : AnyObject]? = nil, headers: [String : String]? = nil ) -&gt; Alamofire.Result&lt;JSON, NSError&gt; {

        Alamofire
            .request(
            httpMethod,
            url,
            parameters: parameters,
            encoding: ParameterEncoding.JSON,
            headers: currentHeaders)

            .responseJSON(completionHandler: { response in
。。。
          }

      return Alamofire.Result.Success(dataJson)
}
</code>

就可以了

->但是此处不是同步的函数,是async的异步函数,所以实际上去改为:

<code>    func getUrlRespJson_async(httpMethod:Alamofire.Method, url:String, parameters: [String : AnyObject]? = nil, headers: [String : String]? = nil, respJsonHandler: (Alamofire.Result&lt;JSON, NSError&gt;)-&gt; Void) {

        Alamofire
            .request(
            httpMethod,
            url,
            parameters: parameters,
            encoding: ParameterEncoding.JSON,
            headers: currentHeaders)

            .responseJSON(completionHandler: { response in
            switch response.result {
            case .Success(let value):
                let valueJson = JSON(value)

                if let code = valueJson["code"].int {
                    if code == 200 {
                        if let dataDict = valueJson["data"].dictionary {

                            let dataJson:JSON = JSON(dataDict)
                            respJsonHandler(Alamofire.Result.Success(dataJson))
                        } else {
                            let emptyDataJson = JSON("")
                            respJsonHandler(Alamofire.Result.Success(emptyDataJson))
                      }
                    } else {
                    }
                }

            case .Failure(let error):
            }
        })
</code>

就可以了。

转载请注明:在路上 » [已解决]swift中result使用出错:Cannot convert call result type Result to expected type Void aka

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.174 seconds, using 22.09MB memory