Switch statement in Swift

I'm learning syntax of Swift and wonder, why the following code isn't working as I expect it to:

for i in 1...100{

    switch (i){
    case 1:
        Int(i%3) == 0
        println("Fizz")
    case 2:
        Int(i%5) == 0
        println("Buzz")
    default:
        println("\(i)")
    }  
}

I want to print Fizz every time number is divisible by 3 (3, 6, 9, 12, etc) and print Buzz every time it's divisible by 5. What piece of the puzzle is missing?

Note: I did solve it using the following:

for ( var i = 0; i < 101; i++){

    if (Int(i%3) == 0){
        println("Fizz")
    }   else if (Int(i%5) == 0){
        println("Buzz")
    }   else {
        println("\(i)")
    }   
}

I want to know how to solve this using Switch. Thank you.


Solution 1:

The usual rules for the FizzBuzz game are to replace every multiple of 3 by "Fizz", every multiple of 5 by "Buzz", and every multiple of both 3 and 5 by "FizzBuzz".

This can be done with a switch statement on the tuple (i % 3, i % 5). Note that _ means "any value":

for i in 1 ... 100 {
    switch (i % 3, i % 5) {
    case (0, 0):
        print("FizzBuzz")
    case (0, _):
        print("Fizz")
    case (_, 0):
        print("Buzz")
    default:
        print(i)
    }
}

Solution 2:

Switch statements in Swift support value bindings.
This allows you to assign a value that matches a certain condition (evaluated via the where clause) to a temporary variable (x & y here):

for i in 1...100 {
    switch (i){
    case let x where x%3 == 0:
        println("Fizz")
    case let y where y%5 == 0:
        println("Buzz")
    default:
        println("\(i)")
    }
}

You could also use the assigned temp value in the case body.

Update:
Matt Gibson points out in the comments, that you can omit the assignment to a temp var if you are not going to use it in the case body.
So a more concise version of the above code would be:

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

Side note: Your 2 code samples are slightly different (the first one uses the range 0-100 as input, while the second one operates on 1-100). My sample is based on your first code snippet.