Learn how to generate random numbers using Swift?
Fortunately, random number generation has been unified since Swift 4.2. Dette betyr at du ikke trenger å bytte rundt med importerte C APIs anymore, du kan ganske enkelt generere tilfeldige verdier ved hjelp av native Swift-metoder på alle plattformer! 😍
As you can see, generating a dice roll is now super easy, thanks to the cryptographically secure randomizer that's built into the Swift language. The new random generator API also better distributing the numbers. The old arc4random function had some issues, because the generated values were not uniformly distributed for example in between 1 and 6 due to the modulo bias side effect. 🎲
Random Number Generator (RNG)
These examples above are implicitly using the default random number generator (SystemRandomNumberGenerator) provided by the Swift standard library. Der er en sekundær parameter for hver metode, så du kan bruge en anden RNG hvis du vil. You can also implement your own RNG or extend the built-in generator, if you'd like to change the behavior of distribution.
Collections, random elements, shuffle [1
9659006] The new random API introduced some nice extensions for collection types. Picking a random element and mixing up the order of elements inside a collection is now ridiculously easy and performant (with custom RNG support as well). 😉
Randomizing custom types
You can implement random functions on your custom types as well. Der er to enkle ting, som du bør huske på for at følge Swift standardbiblioteksmønsteret:
- give en statisk metode, der har en (inout) parameter for den brugerdefinerede RNG
- lav en tilfældig () metode, der bruger the
Generating random values using GameplayKit
The GameplayKit provides lots of things to help you deal with random number generation. Random sources in GameplayKit
GameplayKit has three random source algorithms implemented, the reason behind it is that random number generation is hard, but usually you're going to go with arc4 random source. You should note that Apple recommends resetting the first 769 values (just around it up to 1024 to make it look good) before you use it for something important, otherwise it wi ll generate sequences that can be guessed. 🔑
GKARC4RandomSource – ok performance and randomness
GKLinearCongruentialRandomSource – fixed, less random