Swift: 3 Ways to Get a Random Element from an Array

Updated: April 29, 2023 By: Khue Post a comment

When developing iOS apps (or other types of apps for Apple devices), there might be times when you need to retrieve a random element from a Swift array, such as you are making a music app and you want to play a random song from a list of songs. This concise, example-based article will walk you through a couple of different ways to randomly get an element from a given array. Without any further ado; let’s get started.

Using the randomElement() method

In Swift 4.2 and newer, you can use the built-in method randomElement() on the Collection protocol to get the job done quickly. If your array is empty, it will return an optional.

Example:

let array = ["A", "B", "C", "D", "E"]
if let randomElement = array.randomElement() {
    print(randomElement)
}

The output can be A, B, C, D, or E. Due to the randomness, it isn’t consistent.

Shuffling the array

This technique works fine. You can also shuffle the array using the shuffled() method and then pick the first one or multiple elements using the prefix() method. This is useful if you want more than one random element.

Example:

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

// Get 2 radnom elements from array
let randomElements = array.shuffled().prefix(2)
print(randomElements)

Generating a random index

The strategy here is to generate a random index, an integer between 0 (inclusive) and the length of the array (exclusive), then use this index to select an element. The built-in arc4random_uniform() function can help you create the random index.

Example:

import Foundation

let array = ["Sling", "Academy", "Swift", "iOS"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])

The output can be any among the elements of the input array.

Conclusion

You’ve learned a few approaches to obtaining a random element from a given array in Swift. In my opinion, the first one is neater and more convenient than the others. However, choose the way you like to go with. If you have any questions related to this topic, please comment.

Happy Swifting and have a nice day!