0

I'm trying to implement a struct which is Equatable and has a variable (in this example 'variable2') of type AnyObject that might or not be equatable.

struct MyStruct : Equatable{
    var variable1 : String;
    var variable2 : AnyObject;

}
func == (obj1 : MyStruct, obj2 : MyStruct) -> Bool {

    if(obj1.variable2.conformsToProtocol(Equatable) && obj2.variable2.conformsToProtocol(Equatable)) {
        //...
    } else {
        //...
    }
    return ...
}

At first I was trying to check if variable2 conforms to protocol Equatable, but doing so i get a compile error.

On a different approach I tried to change 'variable2' to Equatablebut even so I still have an error telling me it can only be used as a generic constraint.

struct MyStruct : Equatable{
    var variable1 : String;
    var variable2 : Equatable;

}
func == (obj1 : MyStruct, obj2 : MyStruct) -> Bool {

    return obj1.variable2 == obj2.variable2;
}

I tried some different ways, but didn't manage to get it to work. Does anyone has a solution for this?Solving the first case would be the best situation, but the second might satisfy my needs as well.

Guilherme
  • 503
  • 4
  • 15

2 Answers2

0

Why not use the "is" operator:

if obj1.variable2 is Equatable && obj2.variable2 is Equatable {
...
}
LIProf
  • 436
  • 2
  • 5
0

(a) AnyObject doesn't conforms to Equatable

(b) If you downcast some class which conforms to Equatable to AnyObject, the result is NOT equatable!!

class C: Equatable {
    var i: Int
    init(value: Int){
        i = value
    }
}
func ==(lhs: C, rhs: C)->Bool {
    return 2 * lhs.i == rhs.i
}

let c1 = C(value: 1)
let c2 = C(value: 2)
c1 == c2 // true

let a1 = c1 as AnyObject
let a2 = c2 as AnyObject
// or if you want
// let a1: AnyObject = c1
// let a2: AnyObject = c2

// a1 == a2   // error!!!

a1 as? C == a2 as? C // true

In other words, you are not able to compare two AnyObject. You can check if two references to AnyObject are the same (representing the same instance). But that has nothing with Equatable protocol.

user3441734
  • 16,722
  • 2
  • 40
  • 59