When generating a random CGFloat, I use the following code. Some explanation here
extension CGFloat{
static func randomFloat(from:CGFloat, to:CGFloat) -> CGFloat {
let randomValue: CGFloat = CGFloat(Float(arc4random()) / 0xFFFFFFFF)
return randomValue * (to - from ) + from
}
}
It used to be OK. Works fine now.
There is a warning, after I upgraded to Swift 5.
'4294967295' is not exactly representable as 'Float'; it becomes '4294967296'
to the line of code
let randomValue: CGFloat = CGFloat(Float(arc4random()) / 0xFFFFFFFF)
How to fix it?
As you know Float
has only 24-bits of significand, so 32-bit value 0xFFFFFFFF would be truncated. So, Swift is warning to you that Float
cannot represent the value 0xFFFFFFFF
precisely.
The short fix would be something like this:
let randomValue: CGFloat = CGFloat(Float(arc4random()) / Float(0xFFFFFFFF))
With using Float.init
explicitly, Swift would not generate such warnings.
But the preferred way would be using random(in:)
method as suggested in matt's answer:
return CGFloat(Float.random(in: from...to))
or simply:
return CGFloat.random(in: from...to)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With