刚刚看了一下
AnyHashable
,当您在
Hashable
(你的枚举)
可任意计算的
,它被包装在属性中
base
在内部
可任意计算的
. 因此,它不能直接强制转换回枚举。这里使用
reduce
改造
[AnyHashable:Any]
到
[TestEnum:String]
:
@objc func notificationReceived(_ notification: Notification) {
print("Notification Received")
guard let userInfo = notification.userInfo?.reduce(into: [TestEnum:String](), { (result, entry) in
if let key = entry.key.base as? TestEnum
{
result[key] = entry.value as? String
}
}) else {
print(notification.userInfo)
return
} // Type casting fails here even though userInfo shows a TestEnum key in debugger
print(userInfo[.test])
}
因为
可任意计算的
符合
CustomStringConvertible
,可以铸造到
String
直接。