swift2 Swift:使用未解析的标识符“json”

eqoofvh9  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(203)

我目前正在开发我的第一个iOS应用程序使用Swift 2.0和Xcode 7.0.1。
我得到一个奇怪的小错误,我似乎无法修复:

var err: NSError?

原代号:

//var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary

Swift2重写代码:

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

重写前使用未解析的标识符“json”

if let parseJSON = json {
            var resultValue = parseJSON["status"] as? String
            print("result: \(resultValue)")

            var isUserRegistered:Bool = false;
            if(resultValue=="Success") { isUserRegistered = true; }

            var messageToDisplay:String = parseJSON["message"] as! String!;
            if(!isUserRegistered)
            {
                messageToDisplay = parseJSON["message"] as! String!;
            }

            dispatch_async(dispatch_get_main_queue(),{

                //Display alert message with confirmation.
                var myAlert = UIAlertController(title:"Alert", message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);

                let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.Default){ action in
                    self.dismissViewControllerAnimated(true, completion: nil);
                }

                myAlert.addAction(okAction);
                self.presentViewController(myAlert, animated:true, completion:nil);
            });  
        }

错误在此行抛出:

if let parseJSON = json {

谁能告诉我我哪里做错了吗

gcxthw6b

gcxthw6b1#

变量json仅在do块的范围内可见。
将代码移入do块。
如果代码通过try语句,则parseJSON有效且非可选。

do {
   let parseJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSDictionary {
   print(parseJSON)
   var resultValue = parseJSON["status"] as? String
   print("result: \(resultValue)")

   var isUserRegistered:Bool = false;
   if(resultValue=="Success") { isUserRegistered = true; }

   var messageToDisplay:String = parseJSON["message"] as! String!;
   if(!isUserRegistered)
   {
      messageToDisplay = parseJSON["message"] as! String!;
   }

   dispatch_async(dispatch_get_main_queue(),{

      //Display alert message with confirmation.
      var myAlert = UIAlertController(title:"Alert", message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);

      let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.Default){ action in
          self.dismissViewControllerAnimated(true, completion: nil);
       }

       myAlert.addAction(okAction);
       self.presentViewController(myAlert, animated:true, completion:nil);
   });  

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

相关问题