迅速编程NSErrorPointer错误等

var data: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: error) as NSDictionary; 

这行代码给我错误

 NSError is not convertable to NSErrorPointer. 

所以我想把代码改成:

 var data: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: &error) as NSDictionary; 

这会把NSError错误变成一个NSErrorPointer。 但是,我得到一个新的错误,无法理解它:

 NSError! is not a subtype of '@|value ST4' 

你的NSError必须被定义为一个Optional因为它可以是零:

 var error: NSError? 

你也想要说明在parsing中有错误将返回nil或parsing返回一个数组。 要做到这一点,我们可以使用as? 运营商。

这给我们留下了完整的代码:

 var possibleData = NSJSONSerialization.JSONObjectWithData( responseData, options:NSJSONReadingOptions.AllowFragments, error: &error ) as? NSDictionary; if let actualError = error { println("An Error Occurred: \(actualError)") } else if let data = possibleData { // do something with the returned data } 

如前所述,错误必须定义为可选( https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/buildingcocoaapps/AdoptingCocoaDesignPatterns.html

但是 – 这个代码会发生错误,如果返回nil,那么“作为NSDictionary”将是罪魁祸首:

 var data: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.AllowFragments, error: &error) as NSDictionary; 

你需要像这样做jsonparsing:

 var jsonError : NSError? let jsonResult : AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &jsonError) if let error = jsonError{ println("error occurred: \(error.localizedDescription)") } else if let jsonDict = jsonResult as? NSDictionary{ println("json is dictionary \(jsonDict)") } else if let jsonArray = jsonResult as? NSArray{ println("json is an array: \(jsonArray)") } 

那可行。 还记得json可以作为一个数组来回来。 而不是通过零的选项,你可以通过任何你喜欢的,例如:

 NSJSONReadingOptions.AllowFragments 

如果你喜欢。

现在在beta-3

 var error: AutoreleasingUnsafePointer<NSError?> = nil var data: NSDictionary = NSJSONSerialization.JSONObjectWithData( w, options:.AllowFragments, error: error ) as NSDictionary; 

检查下面的代码:

 var error: AutoreleasingUnsafePointer<NSErrorPointer?>=nil var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil) var err: NSError? var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary println("Result\(jsonResult)") 

尝试使用

  var error: AutoreleasingUnsafePointer<NSErrorPointer?>=nil