Search code examples
swiftloopsenumerate

Swift: enumerated starting at 1?


In Swift, is it possible to enumerate a sequence starting at 1?

In my case, I'm using the SQLite C interface to bind values to prepared statements. The second argument of the sqlite3_bind_*() routines is the index of the SQL parameter to be set. The indices start at 1. (Ie, they're one-based.)

I could use Sequence.enumerated() and just add 1 to n inside each iteration, like so:

for (n, value) in values.enumerated() {
  sqlite3_bind_int(stmt, Int32(n)+1, value)
}

But is there a way to start n from 1?


Solution

  • No, all collections indices in Swift are zero based but if you really want you can create your own custom enumeration zipping a range of Int32 values and the source collection:

    extension Collection {
        var enumerated: Zip2Sequence<PartialRangeFrom<Int32>, Self> { zip(1..., self) }
    }
    

    usage:

    let values: [Int32] = [10, 20, 30]
    
    for (n, value) in values.enumerated {
        print("value:", value, "at:",  n)
    }
    

    This will print

    value: 10 at: 1
    
    value: 20 at: 2
    
    value: 30 at: 3