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

index(_:offsetBy:)

Returns an index that is the specified distance from the given index. 与えられたインデックスから指定された隔たりのインデックスを返します。

Declaration 宣言

func index(_ i: Index, offsetBy distance: Int) -> Index

Parameters パラメータ

i

A valid index of the collection. コレクションのひとつの有効なインデックス。

n

The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. iを補う間隔。nは、そのコレクションがBidirectionalCollectionプロトコルに準拠するのでない限り、負であってはなりません。

Return Value 戻り値

An index offset by n from the index i. If n is positive, this is the same value as the result of n calls to index(after:). If n is negative, this is the same value as the result of -n calls to index(before:). nだけインデックスiから補われるインデックス。nが正ならば、これはnindex(after:)を呼び出すの結果と同じ値です。nが負ならば、これは-nindex(before:)を呼び出すの結果と同じ値です。

Discussion 議論

The following example obtains an index advanced four positions from a string’s starting index and then prints the character at that position. 以下の例は、文字列の開始インデックスから4位置進んだインデックスを取得して、それからその位置の文字を出力します。


let s = "Swift"
let i = s.index(s.startIndex, offsetBy: 4)
print(s[i])
// Prints "t"

The value passed as n must not offset i beyond the bounds of the collection. nとして渡される値は、このコレクションの境界を越えてiを補ってはなりません。

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n. 計算量:O(1)、もしコレクションがRandomAccessCollectionに準拠するならば;そうでなければ、O(n)、そこでnnの値の絶対値です。