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

how can i use a if statement and a for in loop together?

Im trying to print the months of the year using the key variables 123 for jan feb march and i have to do it using for in loop and if statement

2 Answers

If you use my code above but change monthArray to months as that's the variable name given to you in the challenge, then that will work:

var months = [1, 2, 3]

for month in months {
    if (month == 1) {println("January")}
    if (month == 2) {println("February")}
    if (month == 3) {println("March")}
}

what about the loop?

thank you :)

thank you :)

if you need help ask me?

The loop is in there - the second line will iterate through all the items in the months array one at a time. At each pass, the value of month will hold the value in the current array ite being looped. So, month will first be 1, then 2, and so on.

On the first pass, month will be 1 so the first if condition will be met, as 1 == 1 so the code will print out "January". The second pass, month will hold the value 2 so the second if condition is met, and so on.

The variable named month can be named anything - it is just a variable to hold each element of the array whilst the for loop does its job.

Does that make sense?

Steve.

Hi Mohammed,

I'm not sure quite what you're after and this potential solution is not the nicest bit of code in the world.

So, let's start with an array of numbers, 1 to 12 called monthArray. Use the for/in loop to iterate through the collection and test each one with an if statement such as:

var monthArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

for month in monthArray {
    if (month == 1) {println("January")}
    if (month == 2) {println("February")}
    if (month == 3) {println("March")}
}

I got bored on your behalf and stopped at March! You can see how the rest would be completed, I hope.

Is that what you're after? There are neater solutions to this but I guess this is about implementing the code structures, not making nice code. Remember, we're not using the index of the array here, we're using the actual contents at each location. So, monthArray[0] is 1. It could just as easily be Steve or Tuesday, but that location is monthArray[0] and it holds the value of 1.

Hope that helps!

Steve.

its the question in swift basics last part

Can you post a link - I'll have a look for you.

Thanks,

Steve.