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

prefix(through:)

Returns a subsequence from the start of the collection through the specified position. コレクションの始まりから指定された位置までも含む下位シーケンスを返します。

Declaration 宣言

func prefix(through position: Int) -> ArraySlice<Element>

Parameters パラメータ

end

The index of the last element to include in the resulting subsequence. end must be a valid index of the collection that is not equal to the endIndex property. 結果の下位シーケンスの中に含まれることになる最後の要素のインデックス。endはコレクションの有効なインデックスで、endIndexプロパティと等しくないものでなければなりません。

Return Value 戻り値

A subsequence up to, and including, the end position. end位置に至るまでの、そしてそれを含む、下位シーケンス。

Discussion 解説

The resulting subsequence includes the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, and including, that index: 結果となるシーケンスは、位置endでの要素を含みます。以下の例は、整数からなる配列において数40のインデックスを捜して、それからそのインデックスに至るまでの、そしてそれを含めて、配列の冒頭を出力します。


let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(through: i))
}
// Prints "[10, 20, 30, 40]"

Using the prefix(through:) method is equivalent to using a partial closed range as the collection’s subscript. The subscript notation is preferred over prefix(through:). prefix(through:)メソッドを使うことは、部分的な完結範囲をコレクションのもつ添え字として使うことと同等です。添え字表記法は、prefix(through:)よりも好まれます。


if let i = numbers.firstIndex(of: 40) {
    print(numbers[...i])
}
// Prints "[10, 20, 30, 40]"

Complexity: O(1) 計算量:O(1)

See Also 参照

Selecting Elements 要素の選択