如何比较两个通用对象。下面是进行比较的示例代码,这一行 elem > value 抛出一个错误,提示 Could not find overload for '>' that accepts the supplied arguments
func index<T : Equatable>(array: T[], value: T) -> Int {
for (index, elem) in enumerate(array) {
if elem > value {
return index
}
}
return array.count
}
最佳答案
来自 Swift 引用:
The Equatable protocol makes it possible to determine whether two values of the same type are considered to be equal.
There is one required operator overload defined in the protocol: ==.
不保证Equatable
对象必须实现 >
运算符,它解释了您的错误。
看看 Comparable
然而。注意 comparable 只需要重载 <
和 ==
运营商。
但是,如果不是a < b
也不是 a == b
,你可以假设 a > b
.
关于swift - 在 Swift 中比较两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24093081/