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'
最佳答案
自 Swift 1 以来,这些类型和方法发生了很大变化。
NS
前缀被删除- 这些方法现在抛出异常而不是采用错误指针
- 不鼓励使用 NSDictionary。而是使用 Swift 字典
这导致以下代码:
do {
let object = try JSONSerialization.jsonObject(
with: responseData,
options: .allowFragments)
if let dictionary = object as? [String:Any] {
// do something with the dictionary
}
else {
print("Response data is not a dictionary")
}
}
catch {
print("Error parsing response data: \(error)")
}
的,如果你不关心具体的解析错误:
let object = try JSONSerialization.jsonObject(
with: responseData,
options: .allowFragments)
if let dictionary = object as? [String:Any] {
// do something with the dictionary
}
else {
print("Response data is not a dictionary")
}
原始答案
你的 NSError 必须被定义为一个 Optional
因为它可以是 nil:
var error: NSError?
您还需要考虑在将返回 nil
的解析或返回数组的解析中存在的错误。为此,我们可以使用带有 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
}
关于快速编程 NSErrorPointer 错误等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24176383/