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

Please explain the FizzBuzz challenge for swift 2.0?

I am having a lot of troubles on doing the FizzBuzz challenge and if someone could explain the answer that would be awesome.

Thanks.

1 Answer

Hi Kask

Let me start by saying that there are multiple different ways to solve the FizzBuzz problem. I'll show you one way.

First, lets write down what we need to do, it'll make it easier to write out our code.

We have to -

  • return "Fizz" if the number provided is divisible by 3
  • return "Buzz' if the number is divisible by 5
  • return "FizzBuzz" if the number is divisible by both
  • return the number, if the number is not divisible by either number.

Now in order to find out if a number is divisible by something, the easier way to write it out is below.

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

This uses the 'Modulo' operator, to divide n by the number 3, and return the remainder. If the remainder is equal is '0' (that is, if n divides by 5 with NO REMAINDER), then return 'Fizz'

You can combine this into an if let statement, with else if clauses, to roll through the things that we need to do.

Here is my example of a working FizzBuzz solution

func fizzBuzz(n: Int) -> String {
    if (n % 5) == 0 && (n % 3) == 0 {
        return "FizzBuzz"
    } else if (n % 5) == 0 {
        return "Buzz"
    } else if (n % 3) == 0 {
        return "Fizz"
    }
    return "\(n)"
}

The order of the if statement is very important. The if statement is going to go through from top to bottom, so you need to ensure that you put the statement that combines both, at the top, so that if it returns true, the function will return the correct value.

If you put if (n % 5) == 0 && (n % 3) == 0 at the bottom, you'll notice that even if the number is divisible by both 3 & 5, it will return only "Fizz" or "Buzz". This is because the if statement has found one that is true, and has exited the function and returned a String.

I hope this makes sense. Please let me know if you have any questions

Regards

Simon

Thanks for helping me out.