迅速如何检查来自Json的NULL值 [英] swift how can I check for NULL values coming from Json
问题描述
我有一个rest api,并且正在通过Json获取所有数据,然后将其放入IOS TableView中.我的问题是,某些数据在Json
I have a rest api and am getting all data via Json then putting it in a IOS TableView. My issue is that some data is being returned as NULL
in Json
"vote_status":null
我试图快速获取该NULL
值并将其更改为字符串"0",但是这样做很难.到目前为止,我有这个
I am trying to get that NULL
value in swift and change it to a string "0" but am having a hard time doing so . I have this so far
if var vote_status = Stream["vote_status"] as? String {
if (vote_status == (vote_status)[NSNull]) {
vote_status = "0"
}
}
但是我收到此编译错误:
However I get this compile error:
无法用索引类型下标字符串"类型的值 '(NSNull).Type'(aka'NSNull.Type')
Cannot subscript a value of type 'String' with an index of type '(NSNull).Type' (aka 'NSNull.Type')
我这样做是因为 nil 和 null 似乎不起作用,所以我不能这样做.
I am doing this because nil and null does not seem to work so I can't do this.
if (vote_status == nil) ...
推荐答案
您只需要有条件地将字典值强制转换为String,并在出现故障null
的情况下使用Nil合并运算符??
分配"0"
:
You just need to conditionally cast your dictionary value to String and use the Nil Coalescing Operator ??
to assign "0"
in case of failure null
:
let vote_status = Stream["vote_status"] as? String ?? "0"
这篇关于迅速如何检查来自Json的NULL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!