To get a random element from an array in Swift
, you can use the randomElement()
method provided by the Array
class. Here's an example:
main.swift91 chars4 lines
In this example, the randomElement
variable will contain a randomly selected element from the array
. Note that the randomElement()
method returns an optional value, so you should unwrap it using optional binding or force unwrapping if you're sure that the array is not empty.
gistlibby LogSnag