This article gives you a short introduction into generating a random value with arc4random_uniform in Swift.

The function arc4random_uniform(UInt32) returns a random number between 0 and and the given parameter minus 1. So arc4random_uniform(10) will return a value between 1 and 9, but not 10. The parameter is of type UInt32 which is not very common. That makes it often necessary to cast to a value of type Int:

let randomIntValue = Int(arc4random_uniform(10))

In most cases it’s not necessary to write type annotations because Swift can almost always infere the type to be used for that constant or variable.

Let’s see how we can use this function to get a random element of an array with integer values:

// new array with 5 integer values
let myArray: [Int] = [6, 10, 56, 11, 32]

First we get a random index:

let index = Int(arc4random_uniform(UInt32(myArray.count)))

And after that we can determine the corresponding value:

let value = myArray[index]

But this is of course not the only possibility. A smarter way is to use an extension:

extension Array {
    func randomItem() -> Element {
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }
}

And from now on we can get the random value with:

let myRandomValue = myArray.randomItem()