Get Index from for loop looping inside NSManagedObject

时间:2016-05-17 11:16:46

标签: ios swift swift2

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?

2 个答案:

答案 0 :(得分:5)

可能是因为可选类型。试着摆脱这样的选择:

if let questions = RestaurantQuestions.all() {
    for (index, item) in questions.enumerate() {
        print(index) // should print index
        //Doing my stuff
    }
}

答案 1 :(得分:3)

您可以使用.enumerate()在Swift 2.0及更高版本中执行此操作,如下所示:

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

它返回一个带索引的元组和数组中每个项的值。 但是,在这种情况下,RestaurantQuestions.all()必须返回有效数组。