0

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@webmagnets Not that there was anything terribly wrong with your original solution! Quite clever, actually.
Thanks. Unfortunately I am not clever enough to know why it was clever.
Well, having discovered that the outer index was not passing down to the inner loop, you tried to give it a synonym that would pass down to the inner loop. And you succeeded! And since index is nothing but a number, and you've no intention of mutating it or anything weird like that, your solution works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.