简体   繁体   中英

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
}

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM