【发布时间】: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]