28

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?

Michel
  • 10,303
  • 17
  • 82
  • 179

2 Answers2

45

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
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    It is true that by adding the type it works. But if instead of using the ternary operator I use the form if () {...} else {...} then it works without the type. I don't quite see the difference. The information at the disposal of the compiler for type inferring seems to be the same. – Michel Jul 19 '16 at 08:24
  • @Michel: What exactly is the if/else statement that works without the type? – Martin R Jul 19 '16 at 08:32
  • Looking again at what I did, I may have given the type at some point, when declaring the variable. Making what you wrote right. – Michel Jul 24 '16 at 06:35
  • I had same error message, and specifying the full type enum case fixed the issue. But my case was could be inferred automatically, the left side of the assignment was a property of the class so the type was declared. `state = (cats.count == 0) ? .noData(parentNode: pNode) : .content(parentNode: pNode, childCategories: cats)`. @MartinR do you have any idea what this is still unclear for the compiler to infer? – Erfan Jun 24 '17 at 09:49
0

Remove the bracelet seems to works :

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

Tj3n
  • 9,837
  • 2
  • 24
  • 35