Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift 2.0 Collections and Control Flow Control Flow With Conditional Statements FizzBuzz

Whats wrong in this ?

I can't figure out why its not working.

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

1 Answer

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

There's a couple of things, and one is tiny and the other is bigger. They tiny thing is on this line:

else if n % 5 ==0

You need a space between the equals and the 0 otherwise you get a compiler error.

And now for the big thing. Your logic is flawed. Imagine this scenario. We send in the number 30. According to your code it will look at 30 and ask if 30 is evenly divisible by 3. It is, so it returns "Fizz". Keep in mind that once a condition is evaluated to true it never performs any other check. It stops dead in its tracks right there and returns the "Fizz". But what it should return is "FizzBuzz" as it is both divisible by 5 and 3. Try reordering your if else ifs with the check for it being divisible by both first.

Hope this helps!