我在散列一个ReferenceWritableKeyPath
. 散列函数似乎ReferenceWritableKeyPath
在散列密钥路径时也考虑了 的通用属性。我已经包含示例代码来说明为什么这是一个问题:
struct TestStruct<T> {
// This function should only be callable if the value type of the path reference == T
func doSomething<Root>(object: Root, path: ReferenceWritableKeyPath<Root, T>) -> Int {
// Do something
print("Non-optional path: \(path) \(path.hashValue)")
return path.hashValue
}
}
let label = UILabel()
let textColorPath = \UILabel.textColor
let testStruct = TestStruct<UIColor>()
let hash1 = testStruct.doSomething(object: label, path: \.textColor)
let hash2 = textColorPath.hashValue
print("Optional path: \(textColorPath) \(hash2)")
如果你运行上面的代码,你会注意到 hash1 和 hash2 是不同的,尽管它们是指向 UILabel 相同属性的路径。
发生这种情况是因为第一个ReferenceWritableKeyPath
有一个Value
that isUIColor
而第二个ReferenceWritableKeyPath
有一个Value
that isOptional<UIColor>
我的项目要求将ReferenceWritableKeyPath
s 存储在字典中,以便关联对象 (UILabel) 的每个属性只有一个 keyPath。由于哈希值不同,这意味着相同的路径将在字典中存储为 2 个不同的键。
有谁知道我可以让它工作的方法?
~提前谢谢