Get random element from an array in Swift

In this Swift programming tutorial, you are going to learn how to get a random element from an Array. So let’s continue…

Well, it is quite easy to get a random item from a Swift array as Swift already has an in-built method which is randomElement(). Using the randomElement function, we can easily pick a random element from a Swift array.

Now see the example given below:

let colors = ["Red", "Green", "Yellow", "Brown", "Black", "Pink"]
let randomColor = colors.randomElement()!

print(randomColor)

Run this code online

In the above code, we have taken an array “colors” that contains a color name in each element. After that we apply the randomElement() method in the array, store it in a constant “randomColor” and print it in the terminal.

If we run the code above, then we will see a random element in the terminal. In our case it is “Green“:

Green

In our code, the randomElement method plays the main role. Using this we are succesfully able to get the random array element. Now we are going to see many more examples…

You can use the if let statement for the possible nil value of an array. Below is how to do it:

let colorArray = ["Red", "Green", "Yellow", "Brown", "Blue"]

if let randomColor = colorArray.randomElement() {
    print(randomColor)
}

Because your collection might be empty in the array, the return type will be optional. In that case, you will get back nil if the collection had nothing in it.

That means, the code inside the if statement will not run if the array is empty.

In the Swift code below we are testing if the array is empty before getting the random element:

let colorArray = [Int]()

if let randomColor = colorArray.randomElement() {
    print(randomColor)
} else {
    print("Empty array")
}

Output:

Empty array

From the output, it is proven that for an empty array, our code bypasses the statements inside the if statement.

Leave a Reply

Your email address will not be published.