webmagnets
webmagnets

Reputation: 2306

How can I access the parent index in a nested for loop in Swift?

I have the following nested for loop in Swift:

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.
    }
}

How can I access the parent for loop's index?

Upvotes: 0

Views: 179

Answers (1)

matt
matt

Reputation: 536047

Name the inner index something else, such as indexInner. Now the name index is not overshadowed and you can refer to it.

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"
    }
}

The rule is very simple: inner scopes can see everything in the outer scope unless they are overshadowed by redeclaring the same name in the inner scope. So if you want to be able to see the outer scope name, don't redeclare it in the inner scope.

Upvotes: 4

Related Questions