O-mkar O-mkar - 11 months ago 44
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?


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.