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 Collections and Control Flow Control Flow With Conditional Statements FizzBuzz Challenge

Why isnt this code working?

Just curious why this isnt working. have tried several different ways.

fizzBuzz.swift
func fizzBuzz(n: Int) -> String {
  // Enter your code between the two comment markers

    for n in 1...100 {
        if ( n % 3 == 0 ) && ( n % 5 == 0 ) {
            return("FizzBuzz")
        } else if n % 3 == 0 {
            return("Fizz")
        } else n % 5 == 0 {
            return("Buzz")
        }

  // End code
  return "\(n)"
}

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hi Conor,

You are on the right track and very close. There are just a couple of things:

  1. The instruction say not to loop over a range, so you'll need to delete that line.
  2. You shouldn't be using else if and else statements. For this, you will only be using if statements. When you have it the way you do, whatever doesn't pass the first two will have to be in the final else, but that's not the case here. In fact, the instruction say to "not worry about the default case", which is technically what your else is.
  3. Once they are changed, they will need to be on there own line or it will cause a syntax error.

So, if you delete that line and change all three conditionals to if statements, the challenge will pass.

Also, it's a really good idea to stick with proper and conventional formatting for you code. It makes it easier to read and consistency is often key to successful coding. Have a look at the reformatted code and compare. Note where spacing is and is not, where parenthesis are use and where they are not...

Otherwise... nice work! :) :dizzy:

func fizzBuzz(n: Int) -> String {
  // Enter your code between the two comment markers

  if (n % 3 == 0) && (n % 5 == 0) {
    return "FizzBuzz"
  }

  if (n % 3 == 0) {
    return "Fizz"
  }

  if (n % 5 == 0) {
    return "Buzz"
  }

  // End code
  return "\(n)"
}

Thank you so much, this is an amazing explanation ! 10/10 would Jason Anders again.