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

[已解决]Swift代码出错:Cannot invoke ‘start’ with an argument list of type ‘((_) throws -> _)’

Swift crifan 3242浏览 0评论
 [背景]
折腾:
[已解决]Swift代码出错: Call can throw, but it is not marked with try and the error is not handled
期间,代码改为:
        do {
            let opt = try HTTP.POST(LOGIN_URL, parameters: params, requestSerializer: JSONParameterSerializer())
            //opt.onFinish = { response in
            opt.start { response in
                if let err = response.error {
                    print("error: \(err.localizedDescription)")
                    return //also notify app of failure as needed
                }
                print("opt finished: \(response.description)")

                print("response data=\(response.data)")


                let respJsonDict = try NSJSONSerialization.JSONObjectWithData(response.data, options: NSJSONReadingOptions.MutableContainers)
                print("respJsonDict=\(respJsonDict)")

                //longin successfully
                //isLogin = true

            }
        } catch let error {
            NSLog("got an error creating the request: \(error)")

        }
结果又出错:
Cannot invoke ‘start’ with an argument list of type ‘((_) throws -> _)’
如图:
Cannot invoke start with an argument list of type throws
[解决过程]
1.搜:
swift Cannot invoke ‘start’ with an argument list of type ‘((_) throws -> _)’
参考:
好像直接对于:
可能会throw错误的代码,外部嵌套加上do try catch,即可。
去试试:
do{
    let respJsonDict:NSDictionary = try NSJSONSerialization.JSONObjectWithData(response.data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
    print("respJsonDict=\(respJsonDict)")
}
catch{

}
2.其实可以看出来是:
对应的start函数的调用,很特殊。
xxx.start{ xxx in
…
}
的写法,没见过,其实也需要去搞懂的。
但是暂时不去理会了。
有空再折腾。
[总结]
此处代码之所以报错:
Cannot invoke ‘start’ with an argument list of type ‘((_) throws -> _)’
的原因是:
start函数内部的代码:
let respJsonDict:NSDictionary = try NSJSONSerialization.JSONObjectWithData(response.data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
可能会抛异常,但是自己没有do try catch的处理,则默认自动向上抛给了start函数,
则希望start函数是JSONObjectWithData函数的类型:
(data:NSData, options opt:NSJSONReadingOptions) throws

这当然和本身的start函数的定义:

start(completionHandler:((Response) -> Void))
相冲突了。
所以解决是:
start函数内部的,可能会抛异常的代码,自己代码外部,加上do try catch:
do{
 let respJsonDict:NSDictionary = try NSJSONSerialization.JSONObjectWithData(response.data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
 print("respJsonDict=\(respJsonDict)")
 }
 catch{

 }
即可
-》这样异常就被自己的catch所捕获,就不会上升到上层的函数了
-》就不会报此处的错了。

转载请注明:在路上 » [已解决]Swift代码出错:Cannot invoke ‘start’ with an argument list of type ‘((_) throws -> _)’

发表我的评论
取消评论

表情

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

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