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

FizzBuzz function - something I wrote, would like to share.

The function takes 4 arguments: range of values - start and end, and the values for fizz and buzz conditions. Returns an array of values.

func fizzBuzz(start: Int, end: Int, fizzValue: Int, buzzValue: Int) -> [String] {
    var numbersCollection: [String] = []

    for number in start...end {
        switch number {
            case 0: numbersCollection.append("\(number)")
            case _ where number % (fizzValue * buzzValue) == 0: numbersCollection.append("FizzBuzz")
            case _ where number % fizzValue == 0: numbersCollection.append("Fizz")
            case _ where number % buzzValue == 0: numbersCollection.append("Buzz")
            default: numbersCollection.append("\(number)")
        }
    }
    return numbersCollection
}

1 Answer

Hey Andis, I love it man! If I may offer one suggestion though: Add a case to handle 0. 0 shows up as "fizzbuzz".

Hey and thanks! I updated the code to handle 0. However zero is a somewhat dubious case. Obviously 0 divides with any number (except 0) without a remainder. Does that mean 0 is a multiple of 3 and/or 5?

Good job, looks like you fixed it.

You're right though 0 is one of several dubious cases. When the left operand is less than the right operand, the compiler simply returns the left operand. If you want to see how it works you should test it out on the playground. That's what I did to find out how the compiler reacted to abnormal situations.

In your case, the only reason why 0 does not reach the default statement is because you're first case statement tests to see if the result of number % (fizzValue * buzzValue) == 0, which is true. Since the left operand is less than the right, the expression simply returns a 0 (so true).

Let me know if I wasn't clear on something.