I have an array like:
var names: String = [ "Peter", "Steve", "Max", "Sandra", "Roman", "Julia" ]
I would like to get 3 random elements from that array. I'm coming from C# but in swift I'm unsure where to start. I think I should shuffle the array first and then pick the first 3 items from it for example?
I tried to shuffle it with the following extension:
extension Array
{
mutating func shuffle()
{
for _ in 0..<10
{
sort { (_,_) in arc4random() < arc4random() }
}
}
}
but it then says "'()' is not convertible to '[Int]'" at the location of "shuffle()".
For picking a number of elements i use:
var randomPicks = names[0..<4];
which looks good so far.
How to shuffle? Or does anyone have a better/more elegant solution for this?
You could define an extension on Array:
If the initial array may have duplicates, and you want uniqueness in value:
Swift 4.1 and below
Swift 4.2 and above
Xcode 9 • Swift 4
Playground testing
Xcode 8.3.1 • Swift 3.1
I do. Algorithmically better than the accepted answer, which does count-1
arc4random_uniform
operations for a full shuffle, we can simply pick n values in narc4random_uniform
operations.And actually, I got two ways of doing better than the accepted answer:
Better solution
Best solution
The following solution is twice faster than previous one.
for Swift 3.0 and 3.1
for Swift 3.2 and 4.x
Usage:
You could also use arc4random() to just choose three elements from the Array. Something like this:
This is just an example, you could also include logic in the function to get a different name for each one.