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

Erik Luo
Erik Luo
3,810 Points

What's wrong?

I think I'm very close. Why is the FizzBuzz logic incorrect?

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


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

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

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

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

1 Answer

Chase Marchione
Chase Marchione
155,055 Points

Hi Erik,

  • Since you're specifying logic for your else, I'll use else if instead of else.

  • I would write the clause with the multiple conditions first. The reason for this is that any 'n' that divides without a remainder into both 3 and 5 will, therefore, also print something for the if statement that only checks for 3, and the one that only checks for 5. Since we're looking for "Fizz", "Buzz", or "FizzBuzz", and not "FizzFizzBuzz" or "BuzzFizzBuzz":

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

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

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

Hope this helps!