如果我从包含以下
的NSNotification返回了一个词典print(notificationObj.object)
Optional({
age = "<null>";
names = (
David
);
})
然后在尝试将其分配给变量时调用guard else:
guard let categories = notificationObj.object as? [String:[String]] else {
// Gets to here
return
}
如何处理Dictionary键为空的情况。
答案 0 :(得分:2)
你的词典确实包含......
Optional({
age = "<null>";
names = (
David
);
})
......和......
age = ...
为String = String
(值为单String
),names = ( ... )
为String = [String]
(值为String
s的数组。)您无法将其强制转换为[String:[String]]
,因为第一对不适合此类型。这就是您的guard
语句命中else
的原因。
很难回答你的问题。字典包含names
,您希望categories
,names
密钥包含David
,它看起来不像类别,...至少您知道为什么{{1} }点击guard
。
答案 1 :(得分:0)
你的问题不是很清楚。
然而 IF
[String:[String]]
喜欢这个
let devices : [String:[String]] = [
"Computers": ["iMac", "MacBook"],
"Phones": ["iPhone 6S", "iPhone 6S Plus"]
]
然后你可以至少有2个解决方案
if let cars = devices["Car"] {
// you have an array of String containing cars here
} else {
print("Ops... no car found")
}
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) }
}
答案 2 :(得分:-1)
您的打印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]]
。