Instance Method

randomElement()

Returns a random element of the collection.

Declaration

func randomElement() -> Element?

Return Value

A random element from the collection. If the collection is empty, the method returns nil.

Discussion

Call randomElement() to select a random element from an array or another collection. This example picks a name at random from an array:

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement()!
// randomName == "Amani"

This method uses the default random generator, Random.default. The call to names.randomElement() above is equivalent to calling names.randomElement(using: &Random.default).

See Also

Accessing Elements

subscript(Int) -> Element

Accesses the element at the specified position.

var first: Element?

The first element of the collection.

var last: Element?

The last element of the collection.

subscript(Range<Int>) -> ArraySlice<Element>

Accesses a contiguous subrange of the array’s elements.

subscript(Range<Int>) -> Slice<Array<Element>>

Accesses a contiguous subrange of the collection’s elements.

func randomElement<T>(using: inout T) -> Element?

Returns a random element of the collection, using the given generator as a source for randomness.

Beta

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software