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 Basics (retired) Control Flow If Statement

Jeremy Turner
Jeremy Turner
1,567 Points

If someone could give the answer and it explain it, it would be greatly appreciated.

You are provided with a constant array named months that contains 3 consecutive numbers starting at 1. Using a for-in loop and an if statement, print out "January" when you encounter a 1, "February" when you encounter a 2, and finally "March" when you encounter a 3.

Could you maybe go into what you're not getting about the challenge? I'd love to help you along to the answer before resorting to giving it outright.

1 Answer

To start, in case you're unfamiliar with a for-in loop:

From Swift Documentation: "You use the for-in loop to iterate over collections of items, such as ranges of numbers, items in an array, or characters in a string."

In this case, the Code Challenge wants you to go over the array "months", which stores values '1', '2', and '3'. First thing you'll want to do is create the loop, assigning a placeholder variable for whatever you'd like to check. I'll use month in this example:

let months = [1, 2, 3]

for month in months {

}

In a for-in loop, whatever you're checking ("month" variable) will automatically be updated before each iteration. So "month" will be '1', then '2', then '3', the values in the "months" variable.

The Code Challenge then asks you to use an if statement to print certain strings (the names of the months) depending on the value of the "month" variable.

let months = [1, 2, 3]

for month in months {
    if month == 1 {
        println("January")
    }
    // Other if checks go here
}

If you're not familiar with if statements at this point, please refer to past videos, or the Swift Documentation link I've provided above.

I really hope this was an understandable explanation for you. If I covered anything you already knew, I apologize.

Jeremy Turner
Jeremy Turner
1,567 Points

Thanks for breaking that down for me. Very much appreciated.

Any time, Jeremy!

Good luck with the rest of the course :)