Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Swift have one-sided strides?

I want to do something like this:

let sequence1 = stride(from: Int32(2), by: 2)
for (i, address) in zip(sequence1, addresses) {
  sqlite3_bind_int64(stmt, i, address.userID)
  sqlite3_bind_int(stmt, i+1, address.deviceID)
}

But stride(from:by:) doesn't exist.

I know I could just change the first line to:

let sequence1 = stride(from: Int32(2), through: Int32.max, by: 2)

or to:

let sequence1 = sequence(first: Int32(2), next: { $0 + 2 })

And I know Swift has one-sided ranges, such as PartialRangeFrom, but does Swift have one-sided strides?

Related:

  • Iterate over collection two at a time in Swift
  • Swift: What's the best way to pair up elements of an Array
like image 639
ma11hew28 Avatar asked Dec 11 '25 20:12

ma11hew28


1 Answers

No, there are no one-sided strides in Swift.

For a general (lazily evaluated) sequence iterating over every second integer your

let sequence1 = sequence(first: Int32(2), next: { $0 + 2 })

is a simple, clear, and flexible solution. An alternative is

let sequence1 = (Int32(1)...).lazy.map { $0 * 2 }

In your particular case I would simply use a one-sided range:

for (i, address) in zip(Int32(1)..., addresses) {
    sqlite3_bind_int64(stmt, 2 * i, address.userID)
    sqlite3_bind_int(stmt, 2 * i + 1, address.deviceID)
}
like image 174
Martin R Avatar answered Dec 13 '25 13:12

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!