Suppose I have an array and I want to pick one element at random.
What would be the simplest way to do this?
The obvious way would be array[random index]
. But perhaps there is something like ruby's array.sample
? Or if not could such a method be created by using an extension?
Another Swift 3 suggestion
Swift 3
import GameKit
In Swift 2.2 this can be generalised so that we have:
First, implementing static
random
property forUnsignedIntegerType
s:Then, for
ClosedInterval
s withUnsignedIntegerType
bounds:Then (a little more involved), for
ClosedInterval
s withSignedIntegerType
bounds (using helper methods described further below):... where
unsignedDistanceTo
,unsignedDistanceFromMin
andplusMinIntMax
helper methods can be implemented as follows:Finally, for all collections where
Index.Distance == Int
:... which can be optimised a little for integer
Range
s:Swift 4.2 and above
The new recommended approach is a built-in method:
randomElement()
. It returns an optional to avoid the empty case I assumed against previously.If you don't create the array and aren't guaranteed count > 0, you should do something like:
Swift 4.1 and below
Just to answer your question, you can do this to achieve random array selection:
The castings are ugly, but I believe they're required unless someone else has another way.
I find using GameKit's GKRandomSource.sharedRandom() works best for me.
or you could return the object at the random index selected. Make sure the function returns a String first, and then return the index of the array.
Short and to the point.
Riffing on what Lucas said, you could create an extension to the Array class like this:
For example: