15

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
}
Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
Garret Kaye
  • 2,412
  • 4
  • 21
  • 45

3 Answers3

18

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
Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
5

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
Marcus Rossel
  • 3,196
  • 1
  • 26
  • 41
1

arc4random_uniform function returns UInt32. You need to convert it to Int

Function declaration
func arc4random_uniform(_: UInt32) -> UInt32

Solution :
let redDelay:NSTimeInterval = NSTimeInterval(Int(arc4random_uniform(100000)) + delayCounter) / 30000

Kostiantyn Koval
  • 8,407
  • 1
  • 45
  • 58