快速警卫队以空值调用字典键 [英] Swift guard else called on dictionary key with NULL value

查看:61
本文介绍了快速警卫队以空值调用字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我从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 = ... is String = String (value is single String),
  • names = ( ... ) is String = [String] (value is array of Strings).

您不能将其强制转换为 [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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆