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

prefix(_:)

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection. 下位シーケンスを、指定された最大長まで、コレクションの冒頭の要素を含めて返します。

Declaration 宣言

func prefix(_ maxLength: Int) -> Slice<ReversedCollection<Base>>

Parameters パラメータ

maxLength

The maximum number of elements to return. maxLength must be greater than or equal to zero. 返される要素の最大限の数。maxLengthは、ゼロより大きいか等しくなければなりません。

Return Value 戻り値

A subsequence starting at the beginning of this collection with at most maxLength elements. このコレクションの先端で始まる多くともmaxLength要素の下位シーケンス。

Discussion 解説

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection. 最大長がコレクションの要素の数を越えるならば、結果はコレクションの要素すべてを含みます。


let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to select from the beginning of the collection. 計算量:コレクションがRandomAccessCollectionに準拠するならば、O(1);そうでなければ、O(k)、そこでkはコレクションの冒頭から選択する要素の数です。