fabian
fabian

Reputation: 5463

Generate random float between two floats on iPhone 5S

This works fine on iPhone 5 but not on iPhone 5S oder iPad Air.

Could not find an overload for '+' that accepts the supplied arguments

Why?

func randomFloat(from:Float, to:Float) -> Float { 
    let rand:CGFloat = CGFloat(arc4random() % 1000) / 1000
    return (rand) * (to - from) + from
}

Upvotes: 1

Views: 111

Answers (1)

fabian
fabian

Reputation: 5463

The trick is to use CGFloat instead of Float

func randomFloat(from:CGFloat, to:CGFloat) -> CGFloat {
    let rand:CGFloat = CGFloat(arc4random() % 1000) / 1000
    return (rand) * (to - from) + from
}

The problem you're seeing is that CGFloat is aliased to different types depending on the architecture. For 32-bit ARM, (iPhone 4S and 5), it's a Float internally, but for arm64, it's actually a Double. If you just use CGFloat instead of Float for your type casts it will work fine

Upvotes: 3

Related Questions