Instance Method インスタンスメソッド

randomElement()

Returns a random element of the collection. コレクションのある無作為な要素を返します。

Declaration 宣言

func randomElement() -> UInt8?

Return Value 戻り値

A random element from the collection. If the collection is empty, the method returns nil. コレクションからのある無作為な要素。コレクションが空ならば、このメソッドは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: randomElement()を呼び出して、ある無作為な要素を配列または別のコレクションから選んでください。この例は、ある名前を無作為に配列から選び出します:


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

This method is equivalent to calling randomElement(using:), passing in the system’s default random generator. このメソッドは、randomElement(using:)を呼び出して、システムのもつ省略時のランダム生成子を渡すことと等しいです。

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection. 計算量:コレクションがRandomAccessCollectionに準拠するならば、O(1);そうでなければ、O(n)、そこでnはコレクションの長さです。