使用未解决的整数jsonResult

时间:2017-07-06 13:02:25

标签: json swift identifier

每当我尝试修复它时,我都会收到此错误。请帮忙

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

if (jsonResult != nil) { 
    print(jsonResult)
} else {
    // couldn't load JSON, look at error
}

1 个答案:

答案 0 :(得分:0)

jsonResult在创建它的do-try-catch语句之外使用,这就是为什么你无法访问它的原因。这是更正后的代码:

do {
    if let jsonResult = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
        print(jsonResult)
        //The following lines of code is commented out because you have used if let outside to make sure that jsonResult here is not nil.
        //So you do not need to check for it again
        //if (jsonResult != nil) { 
        //   print(jsonResult)
        //} else {
        //    // couldn't load JSON, look at error
        //}
    }

} catch let error as NSError {
    print(error.localizedDescription)
}