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 Solution to FizzBuzz

Otto linden
Otto linden
5,857 Points

Why wont this work?

Why won't this code work?

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)"
}

Can you link me to the challenge, please. My phone isn't cooperating.

4 Answers

Try n = 15 and see if you get Fizz or FizzBuzz. If order is important you should check for FizzBuzz first. In addition to this as explained in the challenge this code is going inside a function - instead of print you should be using return

Otto linden
Otto linden
5,857 Points

Thanks Kris! 🙂

FANG YU
FANG YU
1,719 Points

I think so Priority important if (n % 3 == 0) && (n % 5 == 0) { return "FizzBuzz" }

This was my solution and the compiler passes it without worrying about the order. I only check or cater for 3 conditions the teacher asked for. Would be nice if the teacher can comment!.

func fizzBuzz(n: Int) -> String {

  if (n % 3 == 0) && !(n % 5 == 0) {return "Fizz"} // for fizzBuzz() to return "Fizz" n should only be divisible by 3 this what it means 
  if (n % 5 == 0) && !(n % 3 == 0) {return "Buzz"} // for fizzBuzz() to return "Buzz" n should only be divisible by 5 this what it 
  if (n % 3) == 0 && n % 5 == 0  {return "FizzBuzz"} // here n should a divisible by both 3 and 5

  return "\(n)"
}

print(fizzBuzz(n:15)) // will print FizzBuzz
print(fizzBuzz(n:3)) // will print Fizz
print(fizzBuzz(n:5)) // will print Buzz
print(fizzBuzz(n:2)) // will print 2

Ah. It's the videos my phone objects to. I need a new one. If I'm on the laptop later, I'll have a look.