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

[已解决]Swift代码出错: Call can throw, but it is not marked with try and the error is not handled

Swift crifan 4553浏览 0评论
[问题]
折腾:
[已解决]Swift中如何把HTTP的POST返回的NSData转换为json变量
期间,用代码:
        do {
            let opt = try 。。。
            opt.start { response in
                if let err = response.error {
                    。。。
                }
                。。。
                let respJsonDict = NSJSONSerialization.JSONObjectWithData(response.data, options: NSJSONReadingOptions.MutableContainers)
                print("respJsonDict=\(respJsonDict)")
            }
        } catch let error {
            NSLog("got an error creating the request: \(error)")
        }
结果出错:
Call can throw, but it is not marked with ‘try’ and the error is not handled
如图:
Call can throw but it is not marked with try and the error is not handled
[解决过程]
1.很明显,此处对于
NSJSONSerialization.JSONObjectWithData(response.data, options: NSJSONReadingOptions.MutableContainers)
需要外部加上try。
但是特殊一点的是,此处外部还有个:
do
try
catch
所以此处要搞清楚,如何加对应的try
2.搜:
swift Call can throw, but it is not marked with ‘try’ and the error is not handled
参考:
去试试,结果又遇到了:
3.后来参考:
可以指定对应类型为dictionary:
let respJsonDict:NSDictionary = NSJSONSerialization.JSONObjectWithData(response.data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
[总结]
如果某个函数,某行代码,提示会throw抛出一场,则直接在对应代码处,外部加上try catch的代码就好了:
do {
     xxx = try yyyy // yyyy could be throw error
}
catch{
     //process error
}
然后对于嵌套try…catch的话,则没有任何问题,直接嵌套即可:
do {
     xxx = try yyyy // yyyy could be throw error

     do {
          zzz = try aaaaa // aaaa could be throw error
     }
     catch{
         //process error
     }
}
catch{
     //process error
}
 即可。

转载请注明:在路上 » [已解决]Swift代码出错: Call can throw, but it is not marked with try and the error is not handled

发表我的评论
取消评论

表情

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

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