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
Use
arc4random_uniform(n)
for a random integer between 0 and n-1.Cast the result to Int so you don't have to explicitly type your vars as
UInt32
(which seems un-Swifty).As of iOS 9, you can use the new GameplayKit classes to generate random numbers in a variety of ways.
You have four source types to choose from: a general random source (unnamed, down to the system to choose what it does), linear congruential, ARC4 and Mersenne Twister. These can generate random ints, floats and bools.
At the simplest level, you can generate a random number from the system's built-in random source like this:
That generates a number between -2,147,483,648 and 2,147,483,647. If you want a number between 0 and an upper bound (exclusive) you'd use this:
GameplayKit has some convenience constructors built in to work with dice. For example, you can roll a six-sided die like this:
Plus you can shape the random distribution by using things like GKShuffledDistribution. That takes a little more explaining, but if you're interested you can read my tutorial on GameplayKit random numbers.
@jstn's answer is good, but a bit verbose. Swift is known as a protocol-oriented language, so we can achieve the same result without having to implement boilerplate code for every class in the integer family, by adding a default implementation for the protocol extension.
Now we can do:
and all other integer classes are ok.
Here is a library that does the job well https://github.com/thellimist/SwiftRandom
Without arc4Random_uniform() in some versions of Xcode(in 7.1 it runs but doesn't autocomplete for me). You can do this instead.
To generate a random number from 0-5. First
Then
Use the standard library functions for high quality random numbers:
arc4random()
orarc4random_uniform()
, just as in Objective-C.They are in the
Darwin
module, so if you haven't importedAppKit
,UIKit
, orFoundation
(which import it for you), you will need toimport Darwin
.Swift 4.2
Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types. You can call the
random()
method on numeric types.