← back to blog

Why didn't I think of that?

2024-12-28

I'm sure I would have started with something like...

currentIndex += 1

if(currentIndex == myList.count) {
    currentIndex = 0
}

...then perhaps later I would try to make it a one-liner but sadly introduce complexity...

currentIndex = currentIndex < myList.count - 1 ? currentIndex + 1 : 0

But, I'm not sure why I have never come across this before:

currentIndex = (currentIndex + 1) % myList.count

When I first saw it I knew immediately what it did, yet I've never even thought of using the modulus when incrementing an index value. wild