Ios 从NSManagedObject内的for循环获取索引

Ios 从NSManagedObject内的for循环获取索引,ios,swift,swift2,Ios,Swift,Swift2,我试图在[NSManagedObject]内循环时从for循环获取索引,我在下面的代码中尝试过。任何人都知道如何得到它 错误:类型“[NSManagedObject]”不符合协议“SequenceType” for (index, item) in RestaurantQuestions.all() { print(index) // should print index //Doing my stuff } 有什么办法吗?您可以在Swift

我试图在[NSManagedObject]内循环时从for循环获取索引,我在下面的代码中尝试过。任何人都知道如何得到它

错误:类型“[NSManagedObject]”不符合协议“SequenceType”

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

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

    }

有什么办法吗?

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

for (index, item) in RestaurantQuestions.all()!.enumerate() {
    print(index) // should print index
    //Do your stuff
}
它返回一个元组,其中包含索引和数组中每个项的值。
但是,在这种情况下,
RestaurantQuestions.all()
必须返回有效数组。

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

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

使用@slava的解决方案,它可以处理可选的arraynice答案,但我已经放弃了可选答案。我已经接受了答案,但我对你的两个答案投了赞成票。