To get a uniformly distributed random number in Swift, you can use the arc4random_uniform()
function from the Foundation
library. This function generates a random number between 0 and a specified upper bound (exclusive) and returns it as a UInt32
. You can then convert this number to the desired data type using standard Swift type conversion methods.
Here's an example of how to generate a random CGFloat
between 0 and 1 using arc4random_uniform()
:
main.swift80 chars2 lines
In this example, arc4random_uniform(UInt32.max)
generates a random UInt32
between 0 and UInt32.max
(which is the largest possible value for a UInt32
). This value is then converted to a CGFloat
and divided by UInt32.max
, which normalizes the value to be between 0 and 1. The result is a random CGFloat
with a uniform distribution.
gistlibby LogSnag