Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous use of operator "+"

So I have this little algorithm in my Xcode project and it no longer works - it's telling me that I can't add a number to another number, no matter what I try.

Note:
Everything was working perfectly before I changed my target to iOS 7.0.
I don't know if that has anything to do with it, but even when I switched it back to iOS 8 it gave me an error and my build failed.

Code:

var delayCounter = 100000

for loop in 0...loopNumber {
    let redDelay: NSTimeInterval = NSTimeInterval(arc4random_uniform(100000) + delayCounter) / 30000

    let blueDelay: NSTimeInterval = NSTimeInterval(arc4random_uniform(100000) + delayCounter) / 30000

    let yellowDelay: NSTimeInterval = NSTimeInterval(arc4random_uniform(100000) + delayCounter) / 30000

    let greenDelay: NSTimeInterval = NSTimeInterval(arc4random_uniform(100000) + delayCounter) / 30000
}
like image 451
Garret Kaye Avatar asked Apr 22 '15 12:04

Garret Kaye


2 Answers

The trouble is that delayCounter is an Int, but arc4random_uniform returns a UInt32. You either need to declare delayCounter as a UInt32:

var delayCounter: UInt32 = 100000
let redDelay = NSTimeInterval(arc4random_uniform(100000) + delayCounter) / 30000

or convert the result of arc4random to an Int:

var delayCounter:Int = 100000
let redDelay = NSTimeInterval(Int(arc4random_uniform(100000)) + delayCounter) / 30000
like image 189
Airspeed Velocity Avatar answered Oct 21 '22 02:10

Airspeed Velocity


The function arc4random_uniform returns a UInt32, but delayCounter is of type Int. There is no operator definition for + in Swift, which takes a UInt32 and Int as its parameters though. Hence Swift doesn't know what to do with this occurrence of the + operator - it's ambiguous.

Therefore you'll have to cast the UInt32 to an Int first, by using an existing initializer of Int, which takes a UInt32 as its parameter:

let redDelay:    NSTimeInterval = NSTimeInterval(Int(arc4random_uniform(100000)) + delayCounter) / 30000
let blueDelay:   NSTimeInterval = NSTimeInterval(Int(arc4random_uniform(100000)) + delayCounter) / 30000
let yellowDelay: NSTimeInterval = NSTimeInterval(Int(arc4random_uniform(100000)) + delayCounter) / 30000
let greenDelay:  NSTimeInterval = NSTimeInterval(Int(arc4random_uniform(100000)) + delayCounter) / 30000

A different approach would be to declare delayCounter as a UInt32:

let delayCounter: UInt32 = 100000
like image 42
Marcus Rossel Avatar answered Oct 21 '22 02:10

Marcus Rossel