Sling Academy
Home/Swift/Swift: 3 Ways to Get a Random Element from an Array

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

Last updated: April 29, 2023

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!

Next Article: Swift: 3 Ways to Remove Duplicates from an Array

Previous Article: Swift: Different ways to find the Min/Max of an array

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)