Swift, how to get a random item from an array
By Flavio Copes
Learn how to get a random item from an array in Swift using the randomElement() method, which returns an optional Element from your array.
This tutorial belongs to the Swift series
To get a random item from a Swift array, call the randomElement() method. It’s built into the Array type, no imports needed.
Suppose you have an array in Swift, like this:
let items = [1, 2, 3]
and you want to get a random number out of it.
The Array data type provides the randomElement() function that returns an Element?:
let item = items.randomElement()
Why is the result optional?
Notice the return type is Element?, an optional. Not Element.
The reason: the array could be empty. There’s no item to return from an empty array, so Swift returns nil in that case. The optional forces you to handle it.
The idiomatic way is to unwrap with if let:
let players = ["Ada", "Grace", "Alan"]
if let picked = players.randomElement() {
print("It's your turn, \(picked)")
} else {
print("No players yet")
}
Each run prints a different player. Run it a few times and you’ll see all three names come up.
Be careful with force unwrapping
You might be tempted to skip the optional with !:
let picked = players.randomElement()!
This works while the array has items. But if players is ever empty, the app crashes at runtime with a fatal error.
That’s a realistic bug: the array is filled from user input or a network call, one day it comes back empty, and the crash ships to production. Stick with if let, or provide a fallback with the nil-coalescing operator:
let picked = players.randomElement() ?? "nobody"
What if you need more than one random item?
randomElement() gives you one item, and calling it twice can return the same one.
If you want several distinct items, shuffle the array first with shuffled() and take what you need:
let winners = players.shuffled().prefix(2)
shuffled() returns a new array in random order, leaving the original untouched, and prefix(2) takes the first two items from it.
Related posts about swift: