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 Comparison and Logical Operators

Harold Bellemare
Harold Bellemare
1,466 Points

If/if else clause order (spoiler)

Hopefully my question will make sense.

At first, I tried to follow Amit's instructions sequentially:

  1. If number is divisible by 3, print Fizz
  2. If number is divisible by 5, print Buzz
  3. If number is divisible by both, print FizzBuzz

However, my code would only run if I followed the order 3-1-2, as someone else did in another thread here. Am I missing something, here? Here is what I mean... this is my working code:

import UIKit

let set = 1...20
let f = "Fizz"
let b = "Buzz"

for number in set {
    if (number % 3 == 0) && (number % 5 == 0) {
        print("\(number)\t\(f)\(b)!")
    } else if (number % 3 == 0) {
        print("\(number)\t\(f)!")
    } else if (number % 5 == 0) {
        print("\(number)\t\(b)!")
    } else {
        print(number);
    }
}

1 Answer

Hi Harold,

This is due to the logic of the if statements. If it first takes the number 15 for example and asks if it's divisible by 5, it will say yes and move on to the next number - without asking if it's divisible by 3 or both. That's why you must first ask, 'is number divisible by both 3 and 5'. You can then put the remaining two statements in any order as the number simply can't be divisible by both as if it was, it would have been picked up by your first if statement.

I hope that makes sense - just leave a comment if you need more clarity.

~Ryan.