get a random element from an array in swift

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.swift
let array = [1, 2, 3, 4, 5]
let randomElement = array.randomElement()
print(randomElement)
91 chars
4 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.

related categories

gistlibby LogSnag