我有一些我想放入字典中的类,但是该类不符合Hashable,因此我不能将其用作Swift字典中的键。由于它是一个类,因此可以通过其在内存中的位置来标识它,并且我很乐意使用其标识符,因此类型本身始终不会落入值语义世界。
因此,我宣布将其扩展为
extension SomeGenericType : Hashable {
public var hashValue: Int {
return unsafeAddressOf(self).hashValue
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎还可以,但是Equatable的Hashable继承,所以我也需要实现tha,这是我的第一次尝试:
public func ==(lhs: SomeGenericType, rhs: SomeGenericType) -> Bool {
return unsafeAddressOf(lhs) == unsafeAddressOf(rhs)
}
Run Code Online (Sandbox Code Playgroud)
错误
"Reference to generic type 'SomeGenericType' requires arguments in <...>"
Run Code Online (Sandbox Code Playgroud)
...足够公平,所以让我们这样做
public func ==<T : SomeGenericType >(lhs: T, rhs: T) -> Bool {
return unsafeAddressOf(lhs) == unsafeAddressOf(rhs)
}
Run Code Online (Sandbox Code Playgroud)
现在说
"Reference to generic type 'SomeGenericType' requires arguments in <...>"
Run Code Online (Sandbox Code Playgroud)
嗯,所以我可以使它适用于所有SomeGenericType,无论它得到什么类型。也许我们可以将AnyObject放在那里?
public func ==<T : SomeGenericType<AnyObject>>(lhs: T, rhs: T) -> Bool {
return unsafeAddressOf(lhs) == unsafeAddressOf(rhs)
}
Run Code Online (Sandbox Code Playgroud)
好吧,现在==很高兴,但显然我没有正确实现Hashable,因为我的hashable扩展现在出现错误,提示:
"Type 'SomeGenericType<T>' does not conform to protocol 'Equatable'"
Run Code Online (Sandbox Code Playgroud)
香港专业教育学院尝试摆弄SomeGenericType上的受约束的扩展,但我似乎无法使类型的受约束的扩展采用另一种协议,语言语法似乎不允许它,所以我在这里有点腌
编辑,供参考SomeGenericType定义如下:
class SomeGenericType<T> {
}
Run Code Online (Sandbox Code Playgroud)
正确的语法是
public func ==<T>(lhs: SomeGenericType<T>, rhs: SomeGenericType<T>) -> Bool {
return unsafeAddressOf(lhs) == unsafeAddressOf(rhs)
}
Run Code Online (Sandbox Code Playgroud)
操作数必须的情况下,SomeGenericType对于
同一类型的占位符T。
对于Swift 3,请使用ObjectIdentifier代替unsafeAddressOf。
| 归档时间: |
|
| 查看次数: |
1369 次 |
| 最近记录: |