【发布时间】:2017-05-09 04:24:32
【问题描述】:
有没有办法检查泛型类型是否符合 Equatable?我希望能够检查相同泛型类型的两个对象是否相等,或者相等对它们没有意义。
由于 Equatable 只能用作泛型约束(因为它具有 Self 或 associatedType 要求)我尝试过使用泛型重载:
//If T is equatable, this is more specific so should be called
func equals<T:Equatable>(lhs:T, rhs:T) -> Bool?{
return lhs == rhs
}
//This should only be called if T is not equatable at compile time
func equals<T>(lhs:T, rhs:T) -> Bool?{
return nil
}
这在使用特定类型调用时有效,例如equals(lhs:1, rhs:1) 按预期返回 true。但是,如果在通用上下文中调用它,它总是返回 nil:
func doSomethingThenCheckEquals<T>(lhs:T, rhs:T){
//Do something here which has no type requirements
//Check if the two objects are equal - would usually do something with the result
//This will always use equals<T> and never equals<T:Equatable>, so will always be nil
_ = equals(lhs:lhs, rhs:rhs)
}
有什么方法可以达到预期的效果吗?
此外,根据this answer,编译器从具有动态类型检查的单个实现开始,但在某些情况下可以创建专门的实现。如果编译器创建了一个专门的实现,它的行为是否类似于第一种情况(equals(lhs:1, rhs:1) 返回true)?
【问题讨论】:
-
为什么在调用
equals(lhs:1, rhs:1)时会期待false? -
啊,好点 - 我不会