Ambiguous reference to member '=='

Michel picture Michel · Jul 19, 2016 · Viewed 17.5k times · Source

That must be a basic mistake, but I can't see what is wrong in this code:

.... object is some NSManagedObject ....
let eltType = ((object.valueForKey("type")! as! Int) == 0) ? .Zero : .NotZero

At compile time, I get this message:

Ambiguous reference to member '=='

Comparing an Int to 0 doesn't seem ambiguous to me, so what am I missing?

Answer

Martin R picture Martin R · Jul 19, 2016

The error message is misleading. The problem is that the compiler has no information what type the values .Zero, .NotZero refer to.

The problem is also unrelated to managed objects or the valueForKey method, you would get the same error message for

func foo(value: Int) {
    let eltType = value == 0 ? .Zero : .NotZero // Ambiguous reference to member '=='
    // ...
}

The problem can be solved by specifying a fully typed value

let eltType = value == 0 ? MyEnum.Zero : .NotZero

or by providing a context from which the compiler can infer the type:

let eltType: MyEnum = value == 0 ? .Zero : .NotZero