It will take about 3 minutes to finish reading this article.
In Swift, we can still use the ** arc4random ** method to obtain random numbers. However, it should be noted that:
Arc4random() uses the key stream generator encrypted by Arc4 password to generate a random number in the interval [0, 2 ^ 32). The return type of this function is always UInt32.
1 | let faceCount = 6 |
The above code is not a problem on 64 bit machines, but there is a risk of crash if you may encounter iPhone 5 and its previous devices. In this case, it is relatively safe to use an improved version:
1 | func arc4random_uniform(_: UInt32) -> UInt32 |
It accepts a UInt32 type number as input, and reduces the result to 0 to n-1.
1 | let faceCount: UInt32 = 6 |
The following is a best practice based on Range:
1 | func random(in range: Range<Int>) -> Int { |