swiftrandomarc4randomcgfloat

Swift random float between 0 and 1


In Swift, I'm trying to get a random float between 0 and 1 but I can't seem to get the type conversions to work.

func randomCGFloat() -> CGFloat {
    return CGFloat(arc4random()) / UINT32_MAX
}

I'm getting a 'CGFloat' is not convertible to 'UInt8' error

Running Xcode 6.


Solution

  • Try initializing the divisor as a float as well, a la:

    CGFloat(Float(arc4random()) / Float(UINT32_MAX))