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
I use this code to generate a random number:
In Swift 4.2 you can generate random numbers by calling the
random()
method on whatever numeric type you want, providing the range you want to work with. For example, this generates a random number in the range 1 through 9, inclusive on both sidesAlso with other types
You can use
GeneratorOf
like this:You can do it the same way that you would in C:
randomNumber
is inferred to be of typeUInt32
(a 32-bit unsigned integer)Edit for Swift 4.2
Starting in Swift 4.2, instead of using the imported C function arc4random_uniform(), you can now use Swift’s own native functions.
You can use
random(in:)
to get random values for other primitive values as well; such as Int, Double, Float and even Bool.Swift versions < 4.2
This method will generate a random
Int
value between the given minimum and maximumI would like to add to existing answers that the random number generator example in the Swift book is a Linear Congruence Generator (LCG), it is a severely limited one and shouldn't be except for the must trivial examples, where quality of randomness doesn't matter at all. And a LCG should never be used for cryptographic purposes.
arc4random()
is much better and can be used for most purposes, but again should not be used for cryptographic purposes.If you want something that is guaranteed to be cryptographically secure, use
SecCopyRandomBytes()
. Note that if you build a random number generator into something, someone else might end up (mis)-using it for cryptographic purposes (such as password, key or salt generation), then you should consider usingSecCopyRandomBytes()
anyway, even if your need doesn't quite require that.