Search code examples
swiftswift3tuples

How did an EnumeratedSequence end up being a tuple?


In the code below, (k, v) is a tuple even though enumareted() returns an EnumeratedSequence object. Is it a compiler magic that turns it into a tuple? How can one achieve this via code - converting EnumeratedSequence into tuple?

var str = "Hello, playground"

for (k, v) in str.characters.enumerated() {
    print("\(k) - \(v)")
}

Solution

  • There is no magic or transformation. Nothing changes at all. An EnumeratedSequence is a sequence of tuples (pairs). for merely examines each of those tuples in turn.

    So, in effect (but simplifying, because EnumeratedSequence is "lazy"), "Hello, playground".characters.enumerated() is already:

       [(0,"H"), (1,"e"), ...]
    

    All you're doing with for is cycling through that.

    Indeed, if you were to explore

    Array(str.characters.enumerated())
    

    ...that is exactly what you would see — an array of tuples.

    You could generate the equivalent tuples yourself; for example:

    var str = "Hello, playground"
    for i in 0..<str.characters.count {
        let (k,v) = (i, Array(str.characters)[i])
        print("\(k) - \(v)")
    }
    

    But the point of enumerated is so that you do not have to do that; it is done for you.