Correct handling of NSJSONSerialization (try catch) in Swift (2.0)?

后端 未结 3 1014
自闭症患者
自闭症患者 2020-12-01 12:24

arowmy init works fine in Swift < 2 but in Swift 2 I get a error message from Xcode Call can throw, but it is not marked with \'try\' and the error is not handled

3条回答
  •  北海茫月
    2020-12-01 12:50

    JSONSerialization.JSONObject throws ErrorType and not NSError.

    so the correct catch is

    do {
        let anyObj = try JSONSerialization.JSONObject(with: data, options: []) as! [String:AnyObject]
        // use anyObj here
    } catch let error {
        print("json error: \(error)")
    }
    

    The type of error in catch let error is ErrorType

提交回复
热议问题