如何在swift 3中从NSNotification获取userinfo

Mur*_*m K 6 ios swift swift3 ios10

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

Cannot convert value of type [AnyHashable : Any] to type NSDictionary in coercion.
Run Code Online (Sandbox Code Playgroud)

我的代码是:

  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{

        }
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

实际的userInfo值是["progressPercentage": 0.82530790852915281]打印出来但[AnyHashable("progressPercentage"): 0.82530790852915281]不满足if条件.

编辑:

没有运气notification.userInfo as? [AnyHashable: Any],但现在适合notification.userInfo as? [String: AnyObject]notification.userInfo as? [String: Any]

在此输入图像描述

在此输入图像描述

Anb*_*hik 15

键入转换

在此输入图像描述

使用

 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{

    }
  }
}
 }
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此API参考文档