Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,868 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 :).