Returns a random element of the collection.
SDK
- Xcode 11.0+
Framework
- Swift Standard Library
Declaration
Return Value
A random element from the collection. If the collection is empty, the method returns nil
.
Discussion
Call random
to select a random element from an array or another collection. This example picks a name at random from an array:
This method is equivalent to calling random
, passing in the system’s default random generator.
Complexity: O(1) if the collection conforms to Random
; otherwise, O(n), where n is the length of the collection.