快速警卫队以空值调用字典键 [英] Swift guard else called on dictionary key with NULL value
问题描述
如果我从NSNotification返回了包含以下内容的字典
If I have a Dictionary returned from a NSNotification containing the following
print(notificationObj.object)
Optional({
age = "<null>";
names = (
David
);
})
然后在尝试将其分配给变量时调用警卫:
Then the guard else is called when trying to assign this to a variable:
guard let categories = notificationObj.object as? [String:[String]] else {
// Gets to here
return
}
如何处理字典关键字为null的情况。
How can I handle the case where a Dictionary key is null.
推荐答案
您的字典中确实包含。 ..
Your dictionary does contain ...
Optional({
age = "<null>";
names = (
David
);
})
...和。 ..
-
age = ...
是String =字符串
(值是单个String
), -
names =(。 ..)
是String = [String]
(值是String
s的数组) 。
age = ...
isString = String
(value is singleString
),names = ( ... )
isString = [String]
(value is array ofString
s).
您不能将其强制转换为 [String:[String]]
,因为第一对不适合这种类型。这就是为什么您的后卫
语句达到 else
的原因。
You can't cast it to [String:[String]]
because the first pair doesn't fit this type. This is the reason why your guard
statement hits else
.
很难回答你的问题。字典包含名称
,您想要类别
,名称
键包含 David
,它看起来并不像类别,...至少您知道为什么 guard
命中<$ c的原因$ c> else 。
Hard to answer your question. Dictionary contains names
, you want categories
, names
key does contain David
, which doesn't look like category, ... At least you know why guard
hits else
.
这篇关于快速警卫队以空值调用字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!