How to get user information from NSNotification in swift 3

I got this error in swift3:

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

My code is:

  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{

        }
      }
    }
  }

The actual value of user information ["progressPercentage": 0.82530790852915281], but it is printed as [AnyHashable("progressPercentage"): 0.82530790852915281]and does not meet the condition if.

Edit:

No luck for notification.userInfo as? [AnyHashable: Any]but now works for notification.userInfo as? [String: AnyObject]andnotification.userInfo as? [String: Any]

enter image description here

enter image description here

+4
source share
2 answers

type converson

enter image description here

use

 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{

    }
  }
}
 }

see API reference documents for more information

+10
source

Plase uses a new class Notificationinstead NSNotification.

I do not have my Mac with me, but this should fix the problem.

, Xcode Swift.

0

Source: https://habr.com/ru/post/1658068/


All Articles