I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation in one's own program? Or is there a library that does this that we can use now?
相关问题
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
- UIPanGestureRecognizer is not working in iOS 13
- What does a Firebase observer actually do?
相关文章
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- why 48 bit seed in util Random class?
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Adding TapGestureRecognizer to UILabel in Swift
- Attempt to present UIAlertController on View Contr
Example for random number in between 10 (0-9);
Very easy code - simple and short.
The following code will produce a secure random number between 0 and 255:
You call it like this:
For bigger numbers it becomes more complicated.
This is the best I could come up with:
These methods use an extra random number to determine how many
UInt8
s are going to be used to create the random number. The last line converts the[UInt8]
toUInt16
orUInt32
.I don't know if the last two still count as truly random, but you can tweak it to your likings :)
Here 5 will make sure that the random number is generated though zero to five. You can set the value accordingly.
I used this code:
Since Swift 4.2
There is a new set of APIs:
All numeric types now have the
random(in:)
method that takesrange
.It returns a number uniformly distributed in that range.
TL;DR
Well, what is wrong with the "good" old way?
You have to use imported C APIs (They are different between platforms).
And moreover...
If you use
arc4random()
(to calculate the remainder) likearc4random() % aNumber
, the result is not uniformly distributed between the0
andaNumber
. There is a problem called the Modulo bias.Modulo bias
Normally, the function generates a random number between
0
and MAX (depends on the type etc.). To make a quick, easy example, let's say the max number is7
and you care about a random number in the range0 ..< 2
(or the interval [0, 3) if you prefer that).The probabilities for individual numbers are:
In other words, you are more likely to end up with 0 or 1 than 2. Of course, bare in mind that this is extremely simplified and the MAX number is much higher, making it more "fair".
Details
xCode 9.1, Swift 4
Math oriented solution (1)
Usage of solution (1)
Programmers oriented solution (2)
Usage of solution (2)
Full Sample
Sample result