[英]Swift. How can I deal with null values into json files?
I'm reading json from a URL and, again (I had the same issue with ObjectiveC) the values crash my app. 我正在从URL中读取json,然后(我在ObjectiveC中遇到了同样的问题)这些值使我的应用崩溃了。 I don't have any problems with Strings and Numbers. 我对字符串和数字没有任何问题。 I can println(value) but when I assign the value into a UILabel, it crashes. 我可以使用println(value),但是将值分配给UILabel时会崩溃。
I use this method to read the JSON: 我使用这种方法来读取JSON:
func jsonFromURL(jsonURL: String) -> Dictionary<String, AnyObject> {
var jsonNSURL: NSURL = NSURL(string: jsonURL)
let jsonSource: NSData = NSData(contentsOfURL: jsonNSURL)
var json = NSJSONSerialization.JSONObjectWithData(jsonSource, options:NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>
return json
}
...and this code to assign values into a UILabel inside a custom Cell ...以及此代码可将值分配到自定义单元格内的UILabel中
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {
var regularTextCell:celda = celda(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
var cell:celda = NSBundle.mainBundle().loadNibNamed("celda", owner: self, options: nil)[0] as celda
cell.name.text = myJson["list"]![indexPath.row]!["name"] as String
cell.id.text = "id: " + String(myJson["list"]![indexPath.row]!["id"] as Int)
// THIS line crash because some values of adress are <null>
cell.address.text = myJson["list"]![indexPath.row]!["address"] as String
return cell
}
You can view an example of the JSON at: https://dl.dropboxusercontent.com/u/787784/example.json 您可以在以下位置查看JSON的示例: https : //dl.dropboxusercontent.com/u/787784/example.json
Thanks! 谢谢!
You'll get an exception from syntax like object as String
if object
is not a String
. 你会得到类似的语法异常object as String
,如果object
是不是String
。 You can avoid the exception by using object as? String
您可以通过使用object as? String
来避免异常object as? String
object as? String
which may result in a nil
being assigned into your text
. object as? String
,可能会导致nil
被分配给您的text
。
In your specific case you could use: 在您的特定情况下,您可以使用:
cell.address.text = (myJson["list"]![indexPath.row]!["address"] as? String) ?? "default"
where I've replaced your as
with as?
在那里我已经更换了你as
有as?
and exploited the nil-coalescing operator ??
并利用了零促销运营商??
. 。
I found this solution in online Swift tutorial. 我在在线Swift教程中找到了该解决方案。 It's very nice solution how to deal with null value in Swift. 如何在Swift中处理null值是一个非常好的解决方案。
This is the concept: 这是概念:
let finalVariable = possiblyNilVariable ?? "Definitely Not Nil Variable"
In tutorial example : 在教程示例中:
let thumbnailURL = result["artworkUrl60"] as? String ?? ""
Here is the link for tutorial: http://jamesonquave.com/blog/developing-ios-8-apps-using-swift-interaction-with-multiple-views/ 这是教程的链接: http : //jamesonquave.com/blog/developing-ios-8-apps-using-swift-interaction-with-multiple-views/
You can change the offending line to: 您可以将违规行更改为:
if let address = myJson["list"]![indexPath.row]!["address"] as? String {
cell.address.text = address
}
else {
cell.address.text = ""
}
The as?
as?
operator will cast the value the same way as
would, but if the casting fails, it will instead assign nil
运营商将投价值的方式相同as
会,但如果铸造失败,它将代替分配nil
The if let …
syntax combines this with a check and when the casting fails (and nil is returned) the else block runs instead if let …
语法将此内容与检查结合在一起,当强制转换失败(并返回nil)时,则运行else块
If you use: 如果您使用:
You'll be able to go like this: 您将可以像这样去:
let yourJSON = JSON.fromURL("https://dl.dropboxusercontent.com/u/787784/example.json")
for (i, node) in yourJSON["list"] {
let isnull = node["address"].isNull
println("//[\"list\"][\(i)]:\t\(isnull)")
}
//["list"][0]: false
//["list"][1]: false
//["list"][2]: true
//["list"][3]: false
//["list"][4]: false
//["list"][5]: true
//["list"][6]: false
//["list"][7]: false
//["list"][8]: false
//["list"][9]: false
//["list"][10]: false
//["list"][11]: false
//["list"][12]: true
//["list"][13]: false
//["list"][14]: false
//["list"][15]: false
//["list"][16]: false
//["list"][17]: false
//["list"][18]: false
//["list"][19]: false
No ?
不是?
or !
或!
required and it does not crash on nonexistent nodes. 必需,并且不会在不存在的节点上崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.