Get a random element from an array in Swift


In Swift, we can get a random element from an array using the randomElement() method.

The randomElement() is an in-built method in Swift that can return a random element from a collection. We can use this method to pick a random array element.

Below is the example of getting a random element from an array using the randomElement() method:

let colors = ["Green", "Purple", "Red", "Green"]
// Get a random element
var randomColor = colors.randomElement()!
print(randomColor)

If you run the above program, you will get a random name of a color:

Green

If you look carefully at the above program, you will see that we have used ! after the randomElement method. Using ! knowing the array.count > 0. We are actually checking if the number of elements is more than 0.

Well, in our example the array is not empty. But what if the array doesn’t is empty or null? In that case, first, you have to check if the array is empty or not using the if let statement. below is how you can do it:

let colors = ["Green", "Purple", "Red", "Green"]
if let randomColor = colors.randomElement() {
    print(randomColor)
}

In the above code, we are checking if the array is null or not and then printing the value from the random element.