我想创建一个if语句来检查我的JSON(item_section)是否在某个键上具有空值。
此代码:
let my_dict = item_section[counter].dictionaryValue
print(my_dict["creator"])
在未设置创建者时打印Optional(null)
。
如果设置了它,则会打印创建者的名称,例如:user_729834892
。
如何创建if语句来检查创建者是否为空?
如:
if ((my_dict["creator"]) == nil) { //This line does not work
my_dict["creator"] = "No Maker"
}
答案 0 :(得分:1)
尝试
if my_dict["creator"].type == .Null {
print("creator is null")
}
答案 1 :(得分:0)
JSON
框架在索引字典(JSON对象)时永远不会返回可选项。如果该值不存在,则返回常量JSON.null
,您可以对其进行比较:
if my_dict["creator"] == JSON.null {
my_dict["creator"] = "No Maker"
}
方法isExists
也可以使用
if !my_dict["creator"].isExists() {
my_dict["creator"] = "No Maker"
}
答案 2 :(得分:0)
试试这个
print( my_dict.indexForKey( "creator") )
if (my_dict.indexForKey( "creator") == nil) {
my_dict["creator"] = "No Maker"
}
如果未设置创建者,则函数indexForKey将返回nil。