【问题标题】:How to get userinfo from NSNotification in swift 3如何在 Swift 3 中从 NSNotification 获取用户信息
【发布时间】:2017-02-27 11:00:22
【问题描述】:

我在 swift3 中遇到了这个错误:

Cannot convert value of type [AnyHashable : Any] to type NSDictionary in coercion.

我的代码是:

  func downloadProgress(notification:NSNotification){

    if let userInfo = notification.userInfo as NSDictionary
    {
         print(userInfo) // [AnyHashable("progressPercentage"): 0.82530790852915281]

      if let progressValue = userInfo["progressPercentage"] as? Float {
        if progressValue > 0.01{

        }
      }
    }
  }

实际的 userInfo 值为["progressPercentage": 0.82530790852915281],但打印为[AnyHashable("progressPercentage"): 0.82530790852915281],不满足if 条件。

编辑:

notification.userInfo as? [AnyHashable: Any] 不走运,但现在适用于 notification.userInfo as? [String: AnyObject]notification.userInfo as? [String: Any]

【问题讨论】:

  • notification.userInfo as? [String: AnyObject] 怎么样?
  • 为什么还要投射它?
  • @ozgur,现在可以投射到[String: AnyObject]
  • @MuruganandhamK - 你看到我的回答了吗,我清楚地提到了这一点,如果你知道类型使用 [String: Any] 代表 swift3 ,如果你使用 [String: AnyObject] 这是 swift2
  • @Anbu.Karthik,是的,我用过[String: Any]

标签: ios swift swift3 ios10


【解决方案1】:

类型转换

使用

 func downloadProgress(notification:NSNotification){

if let userInfo = notification.userInfo as [String: Any] // or use if you know the type  [AnyHashable : Any]
{
     print(userInfo) 

  if let progressValue = userInfo["progressPercentage"] as? Float {
    if progressValue > 0.01{

    }
  }
}
 }

有关更多信息,请参阅API Reference Documents

【讨论】:

  • 嗨,@Anbu.Karthik,[AnyHashable : Any] 在这里不工作。 [String: Any][String: AnyObject] 现在支持类型转换
  • 接受你的 :-)
  • @MuruganandhamK - 不是那样,
【解决方案2】:

请使用新类Notification 而不是NSNotification

我没有带我的 Mac,但这应该解决问题。

如果您使用集成的 Xcode Swift 转换工具,则会自动应用此更改。

【讨论】:

  • 嗨@Teejay,问题不在于NotificationNSNotification。都是关于类型转换的
  • 好的,但是如果您使用转换工具,它可能还会将 NSDictionary 转换为正确的 [AnyHashable : Any] 构造。
  • 是的,我明白了。谢谢
猜你喜欢
  • 2010-11-05
  • 2018-05-21
  • 1970-01-01
  • 2022-01-10
  • 2018-02-26
  • 2021-02-09
  • 2012-12-22
  • 1970-01-01
  • 2020-01-15
相关资源
最近更新 更多