Generic Instance Method 総称体インスタンスメソッド

randomElement(using:)

Returns a random element of the collection, using the given generator as a source for randomness. コレクションのある無作為な要素を返します、与えられた生成子を無作為さの出典として使って使います。

Declaration 宣言

func randomElement<T>(using generator: inout T) -> Base.Element? where T : RandomNumberGenerator

Parameters パラメータ

generator

The random number generator to use when choosing a random element. ある無作為な要素を選ぶときに使う無作為数生成子。

Return Value 戻り値

A random element from the collection. If the collection is empty, the method returns nil. このコレクションからのある無作為の要素。コレクションが空ならば、このメソッドはnilを返します。

Discussion 解説

Call randomElement(using:) to select a random element from an array or another collection when you are using a custom random number generator. This example picks a name at random from an array: randomElement(using:)を呼び出して、あなたがあつらえの無作為数生成子を使っている場合に、ある無作為な要素を配列または別のコレクションから選んでください。この例は、ある名前を無作為に配列から選出します。


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

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はコレクションの長さです。