Saturday, April 23, 2016

Swift's enumerate

Swift has this sweet function called "enumerate". This is similar to "for x in array" loop but in addition to providing the element in the array, it also provides index of that element in that array.

The normal for loop is available in C++ as well

for(uint32_t i = 0 ; i < array.size(); i++)
{

}

or the range based for loop where we can get the elements without using index.

for(auto element : Array)
{

}

or the iterator based for loop from which you can calculate the index

for( auto itr = Array.begin(); itr != Array.end(); ++itr)
{
  auto index = itr - Array.begin();

}

But there is no current possible way to get both index and the element at the same time without  a little bit of extra effort by the programmer.

But in Swift 2.0, enumerate() can be used to get the index and element like so.

for(index, elem) in Array.enumerate(){
...

}

Now how cool is that? This would come in handy if you have to iterate through the array, and a second array with same size and aligned elements in correlation with the enumerated array has to be accessed at the same index.

Or if you need the index to erase/delete and element based on some conditions.

for(index, elem) in Array.enumerate(){
  if(condition){
    Array.removeAtIndex(index)
  }

}


That is all for today's post. Hope it was useful to you in one way or the other in understanding a little bit deeper into the programming tactics. 


No comments: