如果我有一个从 NSNotization 返回的字典,其中包含以下内容
print(notificationObj.object)
Optional({
age = "<null>";
names = (
David
);
})
然后,当尝试将其分配给变量时,将调用 else 的守卫:
guard let categories = notificationObj.object as? [String:[String]] else {
// Gets to here
return
}
如何处理字典键为空的情况。
您的字典确实包含...
Optional({
age = "<null>";
names = (
David
);
})
。和。。。
-
age = ...
String = String
(值为单个String
(, -
names = ( ... )
是String = [String]
(值是String
s 的数组(。
您不能将其转换为[String:[String]]
因为第一对不适合此类型。这就是为什么你的guard
陈述击中else
的原因。
很难回答你的问题。字典包含names
,你想要categories
,names
键确实包含David
,看起来不像类别,...至少你知道为什么guard
会打else
.
你的问题不是很清楚。
但是,如果
- 您有一个字典声明如下
[String:[String]]
- 并且您希望管理不存在给定键的情况
喜欢这个
let devices : [String:[String]] = [
"Computers": ["iMac", "MacBook"],
"Phones": ["iPhone 6S", "iPhone 6S Plus"]
]
然后,您至少可以2个解决方案
1. 有条件解包
if let cars = devices["Car"] {
// you have an array of String containing cars here
} else {
print("Ops... no car found")
}
2.后卫让
func foo() {
guard let cars = devices["Car"] else {
print("Ops... no car found")
return
}
// you have an array of String containing cars here...
cars.forEach { print($0) }
}
notificationObject.object 似乎是由如下所示的 JSON 字符串构造的:
"{ "age": null, "names":["David"] }"
你点击 else 子句的原因是 age 实际上是一个 nil,而不是一个有效的 String 数组。 我尝试使用[String: [String]?]
[String: NSArray?]
但似乎都不起作用。该类型实际上是一个 NSNull(继承自 NSObject(。
因此,您可以像这样投射到[String: AnyObject]
并检查 NSArray:
if let categories = j as? [String: AnyObject] where (categories["age"] is NSArray) {
print("age was array")
} else {
print("age is probably null")
}
如果通知对象在值为 null 时仅省略"age"属性,则可能会更好。 然后你就可以投射到[String: [String]]
.