/

How to Get a Random Item from an Array in Swift

How to Get a Random Item from an Array in Swift

In this tutorial, we will learn how to retrieve a random item from an array in Swift. Let’s say we have an array like this:

1
let items = [1, 2, 3]

and we want to extract a random element from it.

In Swift, the Array data type offers a convenient function called randomElement() that returns an optional element (Element?). This function allows us to easily get a random item from an array. To use this function, we can simply do:

1
let item = items.randomElement()

The randomElement() function randomly selects an element from the array and returns it as an optional value. This means that it may return nil if the array is empty.

If you want to ensure that the function always returns a value (i.e., not nil), you can use optional unwrapping or a default value. Here are two examples:

Optional Unwrapping:

1
2
3
4
5
6
7
if let item = items.randomElement() {
// Use the random item here
print(item)
} else {
// Handle the case when the array is empty
print("The array is empty.")
}

Default Value:

1
let item = items.randomElement() ?? defaultValue

In the first example, we use optional unwrapping (if let) to safely unwrap the optional value and perform some actions with the random item if it exists. Otherwise, we handle the case when the array is empty.

In the second example, we use the nil-coalescing operator (??) to provide a default value if randomElement() returns nil. This allows us to assign a default value to item in case the array is empty or randomElement() returns nil.

That’s it! You now know how to get a random item from an array in Swift using the randomElement() function. Feel free to use this method in your projects whenever you need to retrieve a random element from an array.

Tags: Swift, array, randomization