LoginSignup
26
22

More than 5 years have passed since last update.

Swiftでのenumerateの使い方

Last updated at Posted at 2015-08-19

Swift2.0から大域関数のenumerateが消え、SequenceTypeにenumerateが実装されました。
Swift3からはenumerateではなくenumeratedになりました

AppleのAPIより

    /// Returns a sequence of pairs (*n*, *x*), where *n* represents a
    /// consecutive integer starting at zero, and *x* represents an element of
    /// the sequence.
    ///
    /// This example enumerates the characters of the string "Swift" and prints
    /// each character along with its place in the string.
    ///
    ///     for (n, c) in "Swift".characters.enumerated() {
    ///         print("\(n): '\(c)'")
    ///     }
    ///     // Prints "0: 'S'"
    ///     // Prints "1: 'w'"
    ///     // Prints "2: 'i'"
    ///     // Prints "3: 'f'"
    ///     // Prints "4: 't'"
    ///
    /// When enumerating a collection, the integer part of each pair is a counter
    /// for the enumeration, not necessarily the index of the paired value.
    /// These counters can only be used as indices 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.
    ///
    /// This example iterates over the indices and elements of a set, building a
    /// list of indices of names with five or fewer letters.
    ///
    ///     let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
    ///     var shorterIndices: [SetIndex<String>] = []
    ///     for (i, name) in zip(names.indices, names) {
    ///         if name.characters.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.
    ///
    ///     for i in shorterIndices {
    ///         print(names[i])
    ///     }
    ///     // Prints "Sofia"
    ///     // Prints "Mateo"
    ///
    /// - Returns: A sequence of pairs enumerating the sequence.
    public func enumerated() -> EnumeratedSequence<Array<Element>>
}

APIにあるように、以下のような実行結果になります。


for (n, c) in "Swift".characters.enumerated() {
    print("\(n): '\(c)'")
}

// 0: 'S'
// 1: 'w'
// 2: 'i'
// 3: 'f'
// 4: 't'

[Int]型の配列の場合は、以下のようになります。


for (i, ele) in [1, 2, 3, 4].enumerated() {
    print("\(i), \(ele)")
}

// 0, 1
// 1, 2
// 2, 3
// 3, 4
26
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
22