Swift Random Number
In-app development, we often need to generate random numbers to provide randomness to the user. However, Swift 4.2 introduced a new random API that is native to swift. In this article, we will discuss the ways to generate random numbers are. In swift, we can use the random () method for any numeric type to develop the random number.
Let's generate a random number within a given range, inclusive of both sides.
We can also generate Random numbers of type Int, Double, and CGFloat.
We can also use the random() method for Boolean values as well.
Swift also provides shuffle() and shuffled() methods to provide randomness in arrays as shown below.
It prints the shuffled number arrays on the console. However, we can also use the randomElement() method for arrays to get the random element in the array. If the array is empty, it provides nil.
It will print any random element from the nums array on the console.