Getting random elements from a Swift array
Use the randomElement method of the Swift Standard Library to get a random element from an array:
let names = ["Alice", "Bob", "Carol", "Dave", "Eve", "Frank", "Grace", "Heidi"]
if let name = names.randomElement() {
print(name)
}
There is no method to get multiple random elements, but you can get the job done using the shuffled method:
print(names.shuffled().prefix(3))
More information
- Array#randomElement
- Array#shuffled
-
Swift Algorithms package: randomSampleAlternatively, there is a method randomSample in the Swift Algorithms package.
-
Array+SampleFor older iOS versions you can use an extension like Array+Sample.
-
Randomization – GameplayKit Programming GuideThere are also methods in GameplayKit that might come in handy when you want to customize the algorithm used to generate random numbers.