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

enumerated()

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence. ペア (n, x) のシーケンスを返します、そこでnはゼロで開始する連続した数を表して、xはシーケンスの要素を表します。

Declaration 宣言

func enumerated() -> EnumeratedSequence<Array<Element>>

Return Value 戻り値

A sequence of pairs enumerating the sequence. このシーケンスを列挙している、ペアからなるあるシーケンス。

Discussion 解説

This example enumerates the characters of the string “Swift” and prints each character along with its place in the string. この例は文字列「Swift」の文字を列挙します、そして各文字をその文字列でのそれの場所とともに出力します。


for (n, c) in "Swift".enumerated() {
    print("\(n): '\(c)'")
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"

When you enumerate a collection, the integer part of each pair is a counter for the enumeration, but is not necessarily the index of the paired value. These counters can be used as indices only in instances of zero-based, integer-indexed collections, such as Array and ContiguousArray. For other collections the counters may be out of range or of the wrong type to use as an index. To iterate over the elements of a collection with its indices, use the zip(_:_:) function. あなたがあるコレクションを列挙するとき、各ペアの整数部分は列挙のためのカウンタです、しかし必ずしもペアにされた値のインデックスではありません。これらのカウンタはインデックスとして使われることが、ゼロ基盤の、整数インデックスでのコレクション、例えばArrayそしてContiguousArrayなどのインスタンスにおいてのみ可能です。他のコレクションに対してこれらのカウンタは、インデックスとして使うのには範囲外または間違った型になるでしょう。あるコレクションの要素すべてにわたってそれのインデックスで反復するには、zip(_:_:)関数を使ってください。

This example iterates over the indices and elements of a set, building a list consisting of indices of names with five or fewer letters. この例は、ある集合のインデックスと要素のすべてにわたって反復します、5つまたはより少ない文字を持つ名前のインデックスから成るリストを作ります。


let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
var shorterIndices: [Set<String>.Index] = []
for (i, name) in zip(names.indices, names) {
    if name.count <= 5 {
        shorterIndices.append(i)
    }
}

Now that the shorterIndices array holds the indices of the shorter names in the names set, you can use those indices to access elements in the set. 現在、shorterIndices配列はnames集合の中のより短い名前のインデックスを保持します、あなたはそれらのインデックスを使ってこの集合の要素にアクセスできます。


for i in shorterIndices {
    print(names[i])
}
// Prints "Sofia"
// Prints "Mateo"

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

See Also 参照

Iterating Over an Array's Elements 配列の要素すべてに反復する