作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我尝试在 Notification
([TestEnum: String]
) 中传递带有 enum
的字典作为键。不幸的是,在收到通知后将字典类型转换为 [TestEnum: String]
失败。
enum TestEnum {
case test
}
class NotificationTest {
var sender: String = "" {
didSet {
NotificationCenter.default.post(name: Notification.Name(rawValue: "Test"), object: nil, userInfo: [TestEnum.test: "test"])
}
}
init() {
NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived(_:)), name: Notification.Name(rawValue: "Test"), object: nil)
}
@objc func notificationReceived(_ notification: Notification) {
print("Notification Received")
guard let userInfo = notification.userInfo as? [TestEnum: String] else { return } // Type casting fails here even though userInfo shows a TestEnum key in debugger
print(userInfo[.test])
}
}
let test = NotificationTest()
test.sender = "blah"
但是,如果我使用 TestEnum
的 rawValue
作为键,当 notification.userInfo
被转换为 [String : 字符串]
.
最佳答案
刚刚看过AnyHashable
的源代码,当你将Hashable
(你的枚举)转换为AnyHashable
时,它被包裹了在 AnyHashable
内的属性 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])
}
而且因为AnyHashable
符合CustomStringConvertible
,所以可以直接转换为String
。
关于swift - 为什么我不能在通知中传递带有枚举键的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54176744/
我是一名优秀的程序员,十分优秀!