简体   繁体   English

比较Swift中的两个对象

[英]Compare two objects in Swift

How can I compare two generic objects. 如何比较两个通用对象。 Below is sample code of doing a comparison and this line elem > value throws an error saying Could not find overload for '>' that accepts the supplied arguments 下面是进行比较的示例代码,此行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
}

From the Swift Reference: 从Swift参考:

The Equatable protocol makes it possible to determine whether two values of the same type are considered to be equal. Equatable协议可以确定相同类型的两个值是否相等。

There is one required operator overload defined in the protocol: ==. 协议中定义了一个必需的运算符重载:==。

There is no guarantee that Equatable objects have to implement the > operator, which explains your error. 无法保证Equatable对象必须实现>运算符,这可以解释您的错误。

Take a look at Comparable however. 看看Comparable Notice that comparable only needs to overload the < and == operators. 请注意,可比只需要重载<==运算符。

However, if not a < b nor is a == b , you can assume that a > b . 但是,如果不是a < b也不是a == b ,则可以假定a > b

You want Comparable, not Equatable. 您想要可比的,而不是平等的。 Equatable only has == . 等于的只有==

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM