简体   繁体   中英

compare two generic objects on swift 2.0

I have to establish whether the current value is equal to the given comparing value.

public static func Is<TBaseValue, TComparingValue>(baseValue: TBaseValue, comparingValue: TComparingValue) -> Bool
{
    return baseValue == comparingValue
}

I almost try this

public static func Is<TBaseValue: Comparable, TComparingValue: Comparable>(baseValue: TBaseValue, comparingValue: TComparingValue) -> Bool
{
    return baseValue==comparingValue
}

and this

  public static func Is<TBaseValue: Equatable, TComparingValue: Equatable>(baseValue: TBaseValue, comparingValue: TComparingValue) -> Bool
{
    return baseValue == comparingValue
}

but always I have the same result Binary operator cannot be applied....

Equatable doesn't exactly mean that. Think about things that are equatable - Int , for instance. 2 == 2 makes sense. 2 == 3 will return false - but it still makes sense. Now, think of something else that's Equatable - String , for instance.

"abc" == "abc" // true
"acb" == "abc" // false

That's fine - but what about this:

"abc" == 4

An Equatable thing is Equatable to itself - not to everything else. In your example, you're comparing two different types - TBaseValue, TComparingValue .

If you want to compare any values you can use overloading:

static func Is<T: Equatable>(first: T, second: T) -> Bool {
    return first == second
}

static func Is<T1, T2>(first: T1, second: T2) -> Bool {
    return false
}

So the most appropriate function gets called automatically. If the first function cannot be called with the passed parameters than the second one gets called anyhow.

This works in Swift 2.0.

func Is<Any : Equatable>(l: Any, _ r: Any) -> Bool {
    return l == r
}

Is("a", "a") // true
Is("a", "b") // false
Is(1, 1)     // true

It also would work with AnyObject .

For comparing two generics, you can declare the generics such that, types, that are capable to be in the place of your generic type, should conform to Comparable protocol.

struct Heap<T: Comparable>{
var heap = [T]()
mutating func insert(element: T){
heap.append(element)
var index = heap.count - 1
heapify(childIndex: index)
}}

Now we will be able to do:-

if heap[parentIndex] < heap[childIndex] {
//Your code
}

How this works?

As we know, conforming to a protocol means implementing all the required methods in that protocol. Comparable protocol has got all the comparison methods as required parameters, and any type that is implementing Comparable will be able to do a comparison.

Happy coding using Generics

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