0

For a seating chart, I have a configuration of room made of number of seats by bench.

In a count loop for elements (seats), I need to assign each seat to a known bench depending on its capacity.

  • My list of seats is an array.
  • My capacity for each bench is a known var. (Int var)
  • My benchs are also known. (array of benchs)

Imagine my capacity is X seats by bench, (I will then dispatch each seat randomly on each bench), how I can assign a place to the next bench every time my bench is full.

My question is about how to increase by +1 every X seats in a loop.

for _ in seatsList {
    seat?.bench = benchList[i]
    i += 1
    // My first 5 seats in array of persons belong to benchlist[0]
    //How I can assign my next X seats to benchlist[1] every X seats in my array of seats, again and again until the end of my seatsList.
}

I hope my explanation was clear enough.

Creanomy
  • 216
  • 2
  • 12
  • 1
    Possible duplicate of: [How can I do a Swift for-in loop with a step?](https://stackoverflow.com/questions/35556850/how-can-i-do-a-swift-for-in-loop-with-a-step) – pkamb Dec 03 '19 at 21:44

1 Answers1

1

You can use stride and the Strideable protocol for this in Swift:

stride(from:to:by:)

Returns a sequence from a starting value to, but not including, an end value, stepping by the specified amount.

https://developer.apple.com/documentation/swift/1641347-stride

Community
  • 1
  • 1
pkamb
  • 33,281
  • 23
  • 160
  • 191
  • 1
    Thanks a lot @pkamb, I think it will answer my question. I didn't know (yet) this protocol. – Creanomy Dec 03 '19 at 21:56
  • How does this solve the problem? All seats need to be iterated through a regular `for` loop, no? Wouldn't it be more along the lines of `seat?.bench = benchList[i / maxBenchSeatsCount]`? – JustinM Dec 03 '19 at 22:04
  • @JustinM I had a hard time following the specific question, but *"every X seats in a loop"* points to `stride`. – pkamb Dec 03 '19 at 22:07
  • @pkamb, JustinM is right, seats need to be iterated in the main loop. Stride is a part of the answer. But here, it doesn't solve the problem...stride only concerns the bench entity. – Creanomy Dec 03 '19 at 22:30