-2

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) }
}
ada10086
  • 292
  • 5
  • 8
  • The error message is very precise. Your `JSON` initializer can throw, and that isn't handled. – Gereon Apr 17 '19 at 16:43
  • Surely, one of [these many search results](https://stackoverflow.com/search?q=Call+can+throw%2C+but+it+is+not+marked+with+%27try%27+and+the+error+is+not+handled) on the error will help. – rmaddy Apr 17 '19 at 16:43

1 Answers1

3

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) }
staticVoidMan
  • 19,275
  • 6
  • 69
  • 98
  • Problem solved! Thanks a lot! I knew I had to use a do catch but somehow missed (data) in – ada10086 Apr 17 '19 at 16:58
  • @ada10086 You could even do `.map { try! JSON(data: $0) }` but generally you should force unwrap only when you are 100% sure it wont crash. However, in cases involving api responses and parsing, I would not use `try!`. Do catch is safe coding. Safety first. – staticVoidMan Apr 17 '19 at 17:12
  • @ada10086 Also, `fatalError` should be replaced with acceptable fallback logic to handle an exception case to prevent a crash. I chose to do it in the example for the sake of readability in order to show the seriousness of it. – staticVoidMan Apr 17 '19 at 17:16