Holtrod
Holtrod

Reputation: 115

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

Upvotes: 0

Views: 1728

Answers (4)

Sebin Roy
Sebin Roy

Reputation: 844

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

Upvotes: 0

Qbyte
Qbyte

Reputation: 13243

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.

Upvotes: 1

oisdk
oisdk

Reputation: 10091

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.

Upvotes: 2

Mundi
Mundi

Reputation: 80265

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.

Upvotes: 0

Related Questions