如何在swift 3

时间:2016-10-18 08:51:23

标签: ios swift swift3 ios10

我在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]

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:14)

输入转化

enter image description here

使用

 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

答案 1 :(得分:1)

Plase使用新课程Notification代替NSNotification

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

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