Thursday, June 2, 2022

Avoiding Swift’s enumerated()

Natalia Panferova (tweet):

The integer value we get with enumerated() shouldn’t be used as index into the collection unless the collection is zero-based and integer-indexed. It’s a counter that always starts from zero.

Ben Cohen:

zip is better in every way… even when you just want numbers

zip(0…, ingredients) is clearer which way around the pair is

zip(1…, ingredients) if you don’t want to keep doing +1 on a zero base

Nick Lockwood:

Another subtlety is:

collection.reversed().enumerated()

vs

collection.enumerated().reversed()

Thomas Grapperon:

If you’re using swift-algorithms, you can also use .indexed() for a slightly better interface than zip.

Previously:

Comments RSS · Twitter

Leave a Comment