Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift Functions and Optionals Parameters and Tuples Tuples

Robert Sheppard
Robert Sheppard
2,549 Points

How does the n variable change? for n in names { if n == name { found = true } }

The n is defined, but how does it relate to the index in the name array?

2 Answers

William Li
PLUS
William Li
Courses Plus Student 26,865 Points
func searchNames (#name: String) -> (Bool,String) {
    let names = ["Amit","Andrew","Ben","Craig","Dave","Guil","Hampton","Jason","Joy","Kenneth","Nick","Pasan","Zac"]

    var found = (false,"\(name) is not a Treehouse Teacher")

    for n in names {
        if n == name {
            found = (true,"\(name) is a Treehouse Teacher)")
        }
    }

    return found
}

Are you talking about this for loop?

    for n in names {
        if n == name {
            found = (true,"\(name) is a Treehouse Teacher)")
        }
    }

It's quite simple actually, this for loop loops through each item in the names array, at first run of the loop, n becomes 1st item in the array "Amit", on the second run, n becomes "Andrew"... and so on.

And at each run of the loop, it check if n is equal to name that defined as function argument (#name: String), if yes, then set the found to be true.

I think I got confused on this one too. However I think that the problem is that for-next loops are usually numbers and not string variables. I had to think about this for a while. I was under the impression that n was a numerical value, i.e. names.count or something like that. I never thought that something like this could be done. Learning something every day :).