最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Swift代码JSON出错:Call can throw, but it is not marked with ‘try’ and the error is not handled

iOS crifan 5771浏览 0评论

折腾:

【已解决】Xcode编译出错:Module compiled with Swift 4.0.1 cannot be imported in Swift 3.2.3

期间,之前正常工作的代码现在出错:

            if let httpBodyData = response.request?.httpBody {

                let httpBodyJson = JSON(data: httpBodyData)

                gLog.verbose(“httpBodyJson=\(httpBodyJson)”)

swift JSON Call can throw, but it is not marked with ‘try’ and the error is not handled

swift – swiftyjson – Call can throw, but it is marked with ‘try’ and the error is not handled – Stack Overflow

https://stackoverflow.com/questions/44296373/swiftyjson-call-can-throw-but-it-is-marked-with-try-and-the-error-is-not-ha

和自己的:

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

为何之前没问题,现在突然有问题了?

貌似swiftc编译器版本更新(要去严格了?)导致的?

改为:

                do {

                    let httpBodyJson = JSON(data: httpBodyData)

                    gLog.verbose(“httpBodyJson=\(httpBodyJson)”)

                } catch {

                    gLog.warning(“http body data to json failed”)

                }

结果还是提示错误:

好像还是需要去加上try:

                do {

                    let httpBodyJson = try JSON(data: httpBodyData)

                    gLog.verbose(“httpBodyJson=\(httpBodyJson)”)

                } catch {

                    gLog.warning(“http body data to json failed”)

                }

就可以了。

【总结】

代码:

                let httpBodyJson = JSON(data: httpBodyData)

改为:

                do {

                    let httpBodyJson = try JSON(data: httpBodyData)

                    gLog.verbose(“httpBodyJson=\(httpBodyJson)”)

                } catch {

                    gLog.warning(“http body data to json failed”)

                }

即可。

另外一处类似代码改为:

                    if let respJson = try? JSON(data: respData) {

                        gLog.verbose(“respJson=\(respJson)”)

                    }

也是可以的。

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

发表我的评论
取消评论

表情

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

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
95 queries in 0.208 seconds, using 23.31MB memory