简体   繁体   中英

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

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:

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: ==.

There is no guarantee that Equatable objects have to implement the > operator, which explains your error.

Take a look at Comparable however. 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 .

You want Comparable, not Equatable. Equatable only has == .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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