gpt4 book ai didi

swift - 为什么我不能在通知中传递带有枚举键的字典

转载 作者:搜寻专家 更新时间:2023-11-01 06:26:14 25 4
gpt4 key购买 nike

我尝试在 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"

但是,如果我使用 TestEnumrawValue 作为键,当 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com