ios - 如何在 Swift 的嵌套 for 循环中访问父索引?

标签 ios swift for-loop

我在 Swift 中有以下嵌套的 for 循环:

for (index,sentenceObject) in enumerate(sentenceObjectsArray) {
    let sentence = sentenceObject as Sentence
    let sentenceIndex = index
    let wordObjectsArray = sentence.words

    for (index,word) in enumerate(wordObjectsRLMArray) {
        println(sentenceIndex) // Here I would like to access the parent
                               // for loop's index.
    }
}

如何访问父 for 循环的索引?

最佳答案

将内部 index 命名为其他名称,例如 indexInner。现在名称 index 没有被遮挡,您可以引用它。

for (index,sentenceObject) in enumerate(sentenceObjectsArray) {
    let sentence = sentenceObject as Sentence
    let sentenceIndex = index
    let wordObjectsArray = sentence.words

    for (indexInner,word) in enumerate(wordObjectsRLMArray) {
        println(index) 
        // "index" here means the outer loop's "index"
    }
}

规则非常简单:内部作用域可以看到外部作用域中的所有内容,除非通过在内部作用域中重新声明相同的名称来掩盖它们。因此,如果您希望能够看到外部作用域名称,请不要在内部作用域中重新声明它。

关于ios - 如何在 Swift 的嵌套 for 循环中访问父索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28587976/

相关文章:

php - for循环中递增字符有效,递减不?

ios - 垂直滚动具有自调整单元格的 UICollectionView 仅显示一半的单元格

ios - 如何更改我在tableView中设置的图像(_ :willDisplayHeaderView:forSection:)?

iphone - 通过将导航栏设置为通过推送/弹出隐藏来查看大小

swift - 使用 Swift 将 90 MB IPA 文件上传到 AppStore 时出现通信错误

Swift SpriteKit 获取可见帧大小

java - 为什么我不能使用? : operators in the 3rd argument of for loops in Java?

java - 嵌套循环模式返回 null

objective-c - 在 Objective-C 中,除了 DEBUG 之外还有 RELEASE 定义吗?

ios - map View :didDeselectAnnotationView: delegate method getting called before the annotation view is actually deselected