Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

swift - swiftyjson - Call can throw, but it is marked with 'try' and the error is not handled

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The SwiftyJSON initializer throws, the declaration is

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

You have three options:

  1. 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
    }
    
  2. Ignore the error and optional bind the result (useful if the error does not matter).

    if let json = try? JSON(data: data) {
       print(json)
    }
    
  3. 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...