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

nicholasdevereaux
nicholasdevereaux
16,353 Points

Can a switch statement be used here?

Can a switch statement be used here? And can someone provide an example. Thank you!

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

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

2 Answers

Josh Reynolds
Josh Reynolds
10,734 Points

Hey nicholasdevereaux

Here is an example of using a switch statement to run through the loop. If you're not using the values inside the case body you can omit them and run a case _ where statement.

for n in 1...100 {
    switch (n){
    case _ where n%3 == 0 && n%5 == 0:
        print("FizzBuzz")
    case _ where n%3 == 0:
        print("Fizz")
    case _ where n%5 == 0:
        print("Buzz")
    default:
        print("\(n)")
    }
}

I've also seen it been done with switching on a tuple like such

 switch (n%3, n%5) {
    case (0, 0):
        print("FizzBuzz") 
    case(0, _): 
        print("Fizz")
    case(_, 0):
        print("Buzz")
    default:
        print("\(n)")
}

where the _ represents any other value.

Hope that helps!

nicholasdevereaux
nicholasdevereaux
16,353 Points

Thank you! I also should have asked why an IF statement is better. The switch statement I came up with gave me an error stating something about I wasn't providing a bool using integers (sorry I can't remember exactly what the error said). My code looked like this:

switch n { case n % 3 == 0 && n % 5 == 0: print("FizzBuzz") case n % 3 == 0: print("Fizz") case n % 5 == 0: print("Buzz")