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 Basics (retired) Control Flow Exercise: FizzBuzz Generator

Samar Khanna
Samar Khanna
1,757 Points

What will be the code if i wanted to use a switch case code block?

Hi guys, I wanted to know the code for this game if I chose to use the switch command instead?

can you post the code first for us to help you ?

Samar Khanna
Samar Khanna
1,757 Points

'''var gameNumber = 1...30

for inputNumber in gameNumber { if (inputNumber % 3) == 0 && (inputNumber % 5) == 0 { println("FizzBuzz") } else if (inputNumber % 3) == 0 { println("Fizz") } else if (inputNumber % 5) == 0 { println("Buzz") } else { println(inputNumber) } } ''' This is the code i used

1 Answer

David Moran
David Moran
9,617 Points
let fizzbuzz = 1...20

for i in fizzbuzz {
    switch i  {
    case let i where (i % 3 == 0) && (i % 5 == 0): //
        println("FizzBuzz")
    case let i where (i % 3 == 0):
        println("Fizz")
    case let i where (i % 5 == 0):
        println("Buzz")
    default:
        println(i)
    }
}

When you want to use conditionals in a switch statement, use the where statement.

For this specific case, we're asking the variable to be used in a conditional (Use the number 3 then find out whether or not 3 % 3 == 0 is true). If the equation turns out to be true, then we will follow that case. In this case, the case will print out the line "Fizz"

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Statements.html

Samar Khanna
Samar Khanna
1,757 Points

Oh k thx, i didn't know the where statement

David Moran
David Moran
9,617 Points

Not a problem, always glad to help :)

Esmobrander Ozpedelamo
Esmobrander Ozpedelamo
9,136 Points

nice im new to iOS development, didn't know about the where statement, i wonder why they didn't cover that part?, kinda important i believe.