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) -> UInt8? 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. 計算量:コレクションがRandomAccessCollectionに準拠するならば、O(1);そうでなければ、O(n)、そこでnはコレクションの長さです。