O-mkar O-mkar - 2 years ago 77
Swift Question

Get Index from for loop looping inside NSManagedObject

I am trying to get the index from the for loop while looping inside [NSManagedObject] I tried below code. anyone has idea how to get it.

Error : Type '[NSManagedObject]?' does not conform to protocol 'SequenceType'

for (index, item) in RestaurantQuestions.all() {

print(index) // should print index
//Doing my stuff


is there any way to do it?

Answer Source

You can use .enumerate() to do so in Swift 2.0 and over as following :

for (index, item) in RestaurantQuestions.all()!.enumerate() {
    print(index) // should print index
    //Do your stuff

It returns a tuple with index and the value for each item in the array. However RestaurantQuestions.all() must return a valid array in this case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download