Swift: Extra argument 'error' in call

前端 未结 3 2125
广开言路
广开言路 2020-11-22 05:49

I\'m currently developing my first iOS app using Swift 2.0 and Xcode Beta 2. It reads an external JSON and generates a list in a table view with the data. However, I\'m gett

3条回答
  •  死守一世寂寞
    2020-11-22 06:40

    With Swift 2, the signature for NSJSONSerialization has changed, to conform to the new error handling system.

    Here's an example of how to use it:

    do {
        if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
            print(jsonResult)
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }
    

    With Swift 3, the name of NSJSONSerialization and its methods have changed, according to the Swift API Design Guidelines.

    Here's the same example:

    do {
        if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
            print(jsonResult)
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }
    

提交回复
热议问题