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

Ben Masel
Ben Masel
2,004 Points

I do not really no what i am doing here!

I do not get what I'm doing wrong and i don't think i know what I'm doing as well!

fizzBuzz.swift
func fizzBuzz(n: Int) -> String {
  // Enter your code between the two comment markers
var n = 18
if (n % 3 == 0) {
  print("Fizz")
}
  // End code
  return "\(n)"
}
Ben Masel
Ben Masel
2,004 Points

Thank you so much!

1 Answer

Dave Berning
Dave Berning
17,365 Points

Hi Benjamin,

So the idea is to return a string of "Fizz" if a number is divisible by 3, "Buzz" if divisible by 5, and "FizzBuzz" if divisible by both. We can check that by using the remainder operator. If a number is divisible by 3, the remainder of that number will be zero.

We can check each number by using an if-else statement. In if-else statements and switch cases, which ever statement is correct first will get executed; everything else won't. So it's important to write your "FizzBuzz" conditional first.

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, Dave

Ben Masel
Ben Masel
2,004 Points

I completely forgot the if statements!

Ben Masel
Ben Masel
2,004 Points

I just want to check, were we supposed to do 5 and 3 or could we do whatever Integers we liked?

Dave Berning
Dave Berning
17,365 Points

You're supposed to use 3 and 5; it cannot be which ever integer you want. I've done this as an exercise at the University of Cincinnati, so this isn't just a Treehouse original exercise. The idea behind using 3 and 5 is to make sure you are printing "FizzBuzz" when a number is divisible by both. 15 for example is divisible by both 3 and 5. If you print out "Fizz" or "Buzz" for 15 it'll be wrong. It has to be "FizzBuzz".

This exercise is to illustrate the importance of the position of your if and switch case statements.

So for example...

1, 2, Fizz (3), 4, Buzz (5), Fizz (6), 7, 8, Fizz (9), Buzz (10), 11, Fizz (12), 13, 14, FizzBuzz (15).