可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am trying to use swiftyjson and I am getting an Error:
Call can throw, but it is marked with 'try' and the error is not handled.
I have validated that my source JSON is good. I've been searching and cannot find a solution to this problem
import Foundation class lenderDetails { func loadLender() { let lenders = "" let url = URL(string: lenders)! let session = URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else { print ("data was nil?") return } let json = JSON(data: data) print(json) } session.resume() } }
Thank you for all the help!
回答1:
You should wrap it into a do-catch
block. In your case:
do { let session = URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else { print ("data was nil?") return } let json = JSON(data: data) print(json) } } catch let error as NSError { // error }
回答2:
The SwiftyJSON initializer throws
, the declaration is
public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws
You have three options:
Use a do - catch
block and handle the error (the recommended one).
do { let json = try JSON(data: data) print(json) } catch { print(error) // or display a dialog }
Ignore the error and optional bind the result (useful if the error does not matter).
if let json = try? JSON(data: data) { print(json) }
Force unwrap the result
let json = try! JSON(data: data) print(json)
Use this option only if it's guaranteed that the attempt will never fail (not in this case!). Try!
can be used for example in FileManager
if a directory is one of the default directories the framework creates anyway.
For more information please read Swift Language Guide - Error Handling
回答3:
Probably you need to implement do{} catch{}
block. Inside do
block you have to call throwable function with try.