Swiftyjson - Call may throw, but it is marked as "try" and the error is not processed

I try to use swiftyjson and I get an error:

A call may cause, but it is marked as "try", and the error is not processed.

I confirmed that my JSON source is good. I searched and can not 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() } } 

Thanks for the help!

+5
source share
3 answers

You should wrap it in a do-catch . 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 } 
0
source

SwiftyJSON throws initializer, declaration

 public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws 

You have three options:

  • Use the do - catch and handle the error (recommended).

     do { let json = try JSON(data: data) print(json) } catch { print(error) // or display a dialog } 
  • Ignore the error and do not have to bind the result (useful if the error does not matter).

     if let json = try? JSON(data: data) { print(json) } 
  • Force Expand Result

     let json = try! JSON(data: data) print(json) 

    Use this option only if it ensures that the attempt never fails (not in this case!). Try! can be used, for example, in FileManager , if the directory is one of the default directories created by the framework.

For more information, please read the Swift Language Guide - Error Handling

+26
source

Perhaps you need to implement the do{} catch{} . Inside the do block, you must call the throwable function with try.

0
source

Source: https://habr.com/ru/post/1268418/


All Articles