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 FizzBuzz

Thomas McNish
Thomas McNish
10,893 Points

I'm not getting any errors from the compiler, so I'm not sure why my code isn't working.

Here's my code. It worked in Xcode, but I'm not getting it in the Treehouse compiler. What am I doing wrong?

if (n % 3 == 0) {
    return("Fizz")
} else if (n % 5 == 0) {
    return("Buzz")
} else if (n % 3 == 0 && n % 5 == 0) {
    return("FizzBuzz")
} 
fizzBuzz.swift
func fizzBuzz(n: Int) -> String {
  // Enter your code between the two comment markers
  if (n % 3 == 0) {
    print("Fizz")
} else if (n % 5 == 0) {
    print("Buzz")
} else if (n % 3 == 0 && n % 5 == 0) {
    print("FizzBuzz")
} 
  // End code
  return "\(n)"
}

1 Answer

Caleb Kleveter
MOD
Caleb Kleveter
Treehouse Moderator 37,862 Points

This is a rather interesting bug that you have.

The way an if-statement works is the first case is checked. Is it true? If yes, execute the code for that case, then exit the if block. If no, then continue the process through the rest of the cases.

What is happening to you is the number is divisible by 3 or 5, that following code is executed, and it exits the if-statement. The last statement is never reached!

So have this case:

(n % 3 == 0 && n % 5 == 0)

At the top. Problem solved!

Thomas McNish
Thomas McNish
10,893 Points

Ha! That's it! Thank you so much. I knew it had to be logical because there were no compiler errors, but I don't think I would've caught that oversight in a million years, so...thanks for saving me a millions years!