Search code examples
swiftxcodeswifty-json

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


I'm new to Swift and couldn't solve this error at line:

  .map { JSON(data: $0) }
class func liveInfo() -> Observable<JSON> {
    let request = try! URLRequest(url: someURL, method: .get)
    return session.rx
      .data(request: request)
      .map { JSON(data: $0) }
}

Solution

  • SwiftyJSON's JSON(data:) can throw an exception so you have to mark it with try.

    Strict solution:

    .map { (data) in
        do {
            return try JSON(data: data)
        }
        catch {
            fatalError("unable to convert data to JSON")
        }
    }
    

    Loose solution:

    .compactMap { try? JSON(data: $0) }