我在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.
}
}
如何访问父循环索引?
答案 0 :(得分:4)
将内部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"
}
}
规则非常简单:内部作用域可以通过在内部作用域中重新声明相同的名称来查看外部作用域中的所有内容,除非它们被黯然失色。因此,如果您希望能够看到外部范围名称,请不要在内部范围内重新声明它。