Ambiguous use of the "-" operator with two Uint

In Xcode beta 5, when I execute the following code on the playground:

import Swift let a = UInt(0) let b = UInt(0) var string = "" string += a + b > 1 ? "true" : "false" let bool = a - b > 1 string += bool ? "true" : "false" string = a - b > 1 ? "true" : "false" string += a - b > 1 ? //ERROR "true" : "false" 

I get the following error:

 Playground execution failed: /var/folders/ws/cpskvst94cq5fb0vjmljzmkw0000gn/T/./lldb/41335/playground29.swift:10:13: error: ambiguous use of operator '-' string += a - b > 1 ? ^ Swift.-:1:6: note: found this candidate func -<T : Strideable>(lhs: T, rhs: T) -> T.Stride ^ Swift.-:1:6: note: found this candidate func -<T : _DisallowMixedSignArithmetic>(lhs: T, rhs: T) -> T._DisallowMixedSignArithmetic 

Is this intended? Why only the last line causes an error?

+4
source share
2 answers

I don't have a complete answer, but maybe what I found will help someone figure out the rest of it:

a - b can be interpreted as one of the following:

 func -(lhs: UInt, rhs: UInt) -> UInt func -<T : Strideable>(lhs: T, rhs: T) -> T.Stride 

Thus, the result will be either UInt or UInt.Stride . Literal 1 can be interpreted somehow because it works:

 let f: UInt.Stride = 1 

For some unknown reason += does Swift interpret a - b as UInt.Stride instead of UInt . Note that the following value gives the same error:

 let e: UInt.Stride = a - b 

If you use UInt(1) instead of 1 , it works:

 string += a - b > UInt(1) ? "true" : "false" 

I believe this works because it makes Swift see a - b as a result of UInt , because it only has > that accepts two UInt (not UInt.Stride and UInt ). Note if you press 1 as UInt.Stride :

 let f: UInt.Stride = 1 

this gives the same error:

 string += a - b > f ? "true" : "false" 

Another workaround is to use UInt() around a - b :

 string += UInt(a - b) > 1 ? "true" : "false" 
+3
source

This is not intended because there is a dedicated UInt statement for UInt .

 func -(lhs: UInt, rhs: UInt) -> UInt 

There is also no reason why only the last line produces this error.

As a workaround, you can create a new variable:

 let aMinusb = a - b string += aMinusb > 1 ? "true" : "false" 

Note: in Swift 1.2, the error is the same.

0
source

All Articles