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

William Lee
William Lee
1,316 Points

Not sure where the error is

Yep

fizzBuzz.swift
func fizzBuzz(n: Int) -> String {
  // Enter your code between the two comment markers
   switch n {
  case n % 3 = 0: return "Fizz"
  case n % 5 = 0: return "Buzz"
  case n % 3 == 0 && n % 5 == 0: return "FizzBuzz"

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

1 Answer

Hi William,

To use a switch statement, you need to add additional conditions as the switch effectively pivots on a value of n which isn't what you want. The switch of n would define coded routes for each value, or group of values, of n, rather than involving any further manipulation. It is possible, though, with some messing about!

Personally, I'd use a chained if statement for this particular challenge which I'll show you below.

Further, remember that a switch, or an if will return immediately a result is found. So, do the combined test first, i.e. the test of both 3 & 5. Otherwise, if n is 15, the first statement is true (15 % 3 == 0) and you get "Fizz" returned.

Here's one way of using a switch, which isn't pretty:

  switch n {
     case n where (n % 5 == 0 ) && (n % 3 == 0): return "FizzBuzz"
     case n where (n % 3 == 0): return "Fizz"
     case n where (n % 5 == 0): return "Buzz"
     default: break
  }

The nested if statement would look like:

  if n % 3 == 0 && n % 5 == 0{
    return "FizzBuzz"
  } else if n % 3 == 0{
    return "Fizz"
  } else if n % 5 == 0{
    return "Buzz"
  }

I hope that helps.

Steve.