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

Jonathan Lee
Jonathan Lee
1,565 Points

FizzBuzz

Not sure why this case failed to compile. Seemed fine in the playground page.

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

for n in 1...100 {
    if (n%3 == 0) {
        return("Fizz")
    } else if (n%5 == 0){
        return("Buzz")
    } else if (n%3 == 0) && (n%5 == 0){
        return("FizzBuzz")
    } else {
        return(n)
    }
}
  // End code
  return "\(n)"
}

5 Answers

Digvijay Jaiswal
Digvijay Jaiswal
5,565 Points

Try the code below. The reason your code is not working is simple, For example if you type 15 you should be getting FizzBuzz but you won't because your first expression also satisfies that 15 % 3 == 0 and jumps out of the loop. I hope it makes sense.

for n in 1...100 {

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

    } else {
        return(n)
Jonathan Lee
Jonathan Lee
1,565 Points

Thank You, I had just realized this before your answer, but wasn't sure how to fix it. Before I watch the video that answers the challenge, do you know if the same result can be given using switch and/ or while loops instead of if, else if loops?

Digvijay Jaiswal
Digvijay Jaiswal
5,565 Points

I am not sure about while since this is not a while kinda case, but yes we can totally achieve this by switch.

Jonathan Lee
Jonathan Lee
1,565 Points

I attempted it in a playground page, but am having trouble with Bool not matching type Int.

var n: Int = 0

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

Digvijay Jaiswal
Digvijay Jaiswal
5,565 Points

Try to replace the last case with the first.