Find every other element in an array with Swift

The other day somebody asked how they could retrieve every other element in an array using Swift. The solution they had tried was to use a for loop to go through all of the elements and then they would pop those elements off the array.  This seemed to work okay but only when all elements would be subsequent to each other. So an array like [0, 1, 2, 3, 4]  worked fine but when an array looked like  [90, 67, 45, 22, 123, 32] this approach didn’t work.

Luckily, swift has an enumerate function that allows you to loop through an array with both an index and the array value. The solution I eventually came up with was to enumerate the array and get the remainder from dividing the index by two in my loop. I then used that to determine if it was an even er odd index and then I printed the value of the element in the array. This might sound complex but the snippet is short and simple:

Simple enough, right? The enumerate function provides us with a way to loop through an array and get an index easily. That way we can write a clean for loop without doing something like var i = 0; i < array.count; i++ for example.

If you have questions about this you can send me a tweet and I’ll try to help. Happy Swifting!