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. このコレクションからのある無作為の要素。コレクションが空ならば、このメソッドは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. 計算量:O(1)、もしコレクションがRandomAccessCollectionに準拠するならば;そうでなければ、O(n)、そこでnはコレクションの長さです。

See Also 参照

Accessing Elements 要素にアクセスする