Basic knowledge of swift-how to use try, try? and try!
try the first way to use try do catch
let data: Data = Data() do { let responseJSON = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]] print(responseJSON) } catch { print("something is wrong here. Try connecting to the wifi.") }
The second way to use try try?
let data: Data = Data() let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] if responseJSON != nil { print("Yeah, We have just unwrapped responseJSON!") } else { print(responseJSON ?? "") }
The third way to use try guard try?
let data: Data = Data() func getResponseJSON() { guard let responseJSON = try? (JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]) else { return } print(responseJSON) }
try The fourth way to use try!
let data: Data = Data() let responseJSON = try! JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]] print(responseJSON)
to sum up
try needs to be used in conjunction with do...catch, this way you can use more detailed error handling methods
try? Ignore our errors, if they happen to happen, set them to nil
try! Open your code and ensure that our function will never encounter errors.In the case that our function does throw an error, our application will only crash.Be careful when using this method
0 Comments