Generic Subscript

subscript(_:)

Accesses the contiguous subrange of the collection’s elements specified by a range expression. 範囲式によって指定される、コレクションの要素からなる連続した下位範囲にアクセスします。

Declaration 宣言

subscript<R>(r: R) -> Slice<ReversedCollection<Base>> where R : RangeExpression, Index == R.Bound { get }

Parameters パラメータ

bounds

A range of the collection’s indices. The bounds of the range must be valid indices of the collection. コレクションのもつインデックスのある範囲。この範囲の境界は、コレクションの有効なインデックスでなければなりません。

Discussion 解説

The range expression is converted to a concrete subrange relative to this collection. For example, using a PartialRangeFrom range expression with an array accesses the subrange from the start of the range expression until the end of the array. 範囲式は、このコレクションに関連するある具体的な下位範囲へ変換されます。例えば、PartialRangeFrom範囲式をある配列で使うことは、その下位範囲に範囲式の始まりから配列の終わりまでにアクセスします。


let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2...]
print(streetsSlice)
// ["Channing", "Douglas", "Evarts"]

The accessed slice uses the same indices for the same elements as the original collection uses. This example searches streetsSlice for one of the strings in the slice, and then uses that index in the original array. アクセスされるスライス(切り取り)は、同じ要素に対して元のコレクションが使うのと同じインデックスを使います。この例は、streetsSliceをスライスの中の文字列の1つについて検索して、それからそのインデックスを元々の配列において使います。


let index = streetsSlice.firstIndex(of: "Evarts")    // 4
print(streets[index!])
// "Evarts"

Always use the slice’s startIndex property instead of assuming that its indices start at a particular value. Attempting to access an element by using an index outside the bounds of the slice’s indices may result in a runtime error, even if that index is valid for the original collection. 常にスライスのstartIndexプロパティを使ってください、それのインデックスが特定の値で始まると決めてかかるのではなく。ある要素にスライスのもつインデックスの境界外のインデックスを使ってアクセスを試みることは、実行時エラーという結果になるでしょう、たとえそのインデックスが元々のコレクションに対して有効であるとしてもです。


print(streetsSlice.startIndex)
// 2
print(streetsSlice[2])
// "Channing"


print(streetsSlice[0])
// error: Index out of bounds

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