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

Edward Laurenson
Edward Laurenson
4,278 Points

Why does this code not work for "FizzBuzz" swift 3

I can't think of a way to do this challenge. Can someone tell me whats wrong with this code?

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

      if n % 3 == 0 {
        print("Fizz")

    }

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

    if n % 3 == 0 && n % 5 == 0{
        print("FizzBuzz")
    }
  // End code
  return "\(n)"
}

2 Answers

You need to put the "FizzBuzz" condition first.

This is because if the number was a multiple of 3 and 5, it would first go in to the fizz condition (not the fizzbuzz condition) because it is a multiple of 3, and return only "fizz"!

This is why you have to put the FizzBuzz condition first.

Also, you are printing the string when you're supposed to return the string :)

fizzbuzz.swift
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)"
}

I hope this helps. ~Alex

Chase Marchione
Chase Marchione
155,055 Points

Hi Edward,

I recommend writing the logic for the 'and' condition first. Since the return values that the compiler is looking for are "Fizz", "Buzz", and "FizzBuzz", we can avoid getting "FizzFizzBuzz" or "BuzzFizzBuzz" this way (since we're checking for the condition in which both values are true first, and returning out of the if clause if they are.)

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

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

    else if (n % 5 == 0) {
      return "Buzz"
    }
  // End code
  return "\(n)"
}

Hope this helps!

Edward Laurenson
Edward Laurenson
4,278 Points

Thanks CJ I recognised the error when I used FizzBuzz(15) in the playground to check