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

prefix(upTo:)

Returns a subsequence from the start of the collection up to, but not including, the specified position. コレクションの始まりから指定された位置まで、しかしそれは含めない下位シーケンスを返します。

Declaration 宣言

func prefix(upTo end: Index) -> Slice<ReversedCollection<Base>>

Parameters パラメータ

end

The “past the end” index of the resulting subsequence. end must be a valid index of the collection. 結果のシーケンスの「終わりを過ぎた」インデックス。endはコレクションのひとつの有効なインデックスでなければなりません。

Return Value 戻り値

A subsequence up to, but not including, the end position. end位置に至るまでの、しかしそれを含まないシーケンス。

Discussion 解説

The resulting subsequence does not include 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, but not including, that index: 結果となるシーケンスは、位置endでの要素を含みません。以下の例は、整数からなる配列において数40のインデックスを捜して、それからそのインデックスに至るまでの、しかしそれを含めずに、配列の冒頭を出力します。


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

Passing the collection’s starting index as the end parameter results in an empty subsequence. コレクションの開始インデックスをendパラメータとして渡すことは、空のシーケンスという結果になります。


print(numbers.prefix(upTo: numbers.startIndex))
// Prints "[]"

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


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

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