问题
I'm currently developing my first iOS app using Swift 2.0 and Xcode 7.0.1.
I'm getting a strange little error that I can't seem to fix:
var err: NSError?
The original code:
//var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
Swift2 rewrite code:
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print(json)
}
} catch {
print(error)
}
Use of unresolved identifier 'json' before rewriting
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);
});
}
The error is thrown at this line:
if let parseJSON = json {
Can someone please tell me what I'm doing wrong here?
回答1:
the variable json
is visible only in the scope of the do
block.
Move the code into the do
block.
Optional bindings is not needed, too. If the code passes the try
statement, parseJSON
is valid and non-optional.
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)
}
来源:https://stackoverflow.com/questions/33253340/swift-use-of-unresolved-identifier-json