Search code examples
iosswiftoperatorsarithmetic-expressions

Ambiguous reference to member '=='


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?


Solution

  • 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