Swift:使用未解析的标识符"json" [英] Swift : Use of unresolved identifier 'json'
本文介绍了Swift:使用未解析的标识符"json"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在使用Swift 2.0和Xcode 7.0.1开发我的第一个iOS应用.
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?
原始代码:
//var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
Swift2重写代码:
Swift2 rewrite code:
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print(json)
}
} catch {
print(error)
}
在重写之前使用未解析的标识符'json'
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);
});
}
此行引发错误:
if let parseJSON = json {
有人可以告诉我我在做什么错吗?
Can someone please tell me what I'm doing wrong here?
推荐答案
变量json
仅在do
块的范围内可见.
the variable json
is visible only in the scope of the do
block.
将代码移到do
块中.
也不需要可选的绑定.如果代码通过try
语句,则parseJSON
有效且非可选.
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)
}
这篇关于Swift:使用未解析的标识符"json"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文