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 2.0 Collections and Control Flow Control Flow With Conditional Statements Working with Logical Operators

Sachin Modgill
Sachin Modgill
850 Points

how do you write a if statement inside a loop? Doesn't the if statement create the loop?

unfortunately i am stuck with the entire question...

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

No, an if statement is not a loop. A loop will continue to run until some condition is met that breaks it. Now that break could be dependent on the outcome of an if statement. But an if statement is its own thing. I'll show you the code and then try to break it down for you.

var results: [Int] = []

for n in 1...100 {
    // Enter your code below
    if (n % 2 != 0) && (n % 7 == 0) {
      results.append(n)
    } 
    // End code 
}

This is what this code translates to in English. Start with an empty list named "results". Start at one and go to 100. Is one odd and divisible by seven? No. Etc until we get to 7. Is seven odd and evenly divisible by 7? Yes! Put that in our results list. And now we check 8... 9... 10 etc. All the way up to 100. Hope this makes sense!

Sachin Modgill
Sachin Modgill
850 Points

thank you, this made a lot of sense