Subscript

subscript(_:)

Accesses a contiguous subrange of the collection’s elements. コレクションのもついくらかの要素からなるある連続した下位範囲にアクセスします。

Declaration 宣言

subscript(bounds: Range<Slice<Base>.Index>) -> Slice<Base> { get }

Parameters パラメータ

bounds

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

Discussion 解説

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..<5]
print(streetsSlice)
// ["Channing", "Douglas", "Evarts"]

The accessed slice uses the same indices for the same elements as the original collection. 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 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)

Relationships 関係