For the bonus portion of the Chapter 6 Silver challenge I used three values in the tuple for the switch statement. By the way the value I is printed beside the FIZZ, BUZZ, FIZZBUZZ. Maybe someone might find this useful.
for i in 1…100
{
var valuethree : Int = 0
var valuefive : Int = 0
var valThreeFive : Int = 0
if (i % 3 == 0 && i % 5 == 0)
{
valThreeFive = i
}
else if (i % 3 == 0)
{
valuethree = i
}
else if (i % 5 == 0)
{
valuefive = i
}
let matches = (valThreeFive, valuethree, valuefive)
switch matches
{
case (valThreeFive, _, _) where valThreeFive == i:
print("\(i)FIZZBUZZ")
case(_, valuethree, _) where valuethree == i:
print("\(i)FIZZ")
case(_,_, valuefive) where valuefive == i:
print("\(i)BUZZ")
default:
print(i)
}
That’s a rather convoluted way of using a switch statement to solve this problem. There are really only two things the switch statement needs to look at: whether i is a multiple of 3 and whether i is a multiple of 5. So your tuple only needs two boolean values indicating whether those two things are true or false. Your switch statement simply checks the 4 combinations of true/false values for the tuple:
for i in 1...100
{
let multipleOfThree : Bool = (i % 3 == 0)
let multipleOfFive : Bool = (i % 5 == 0)
let matches = (multipleOfThree, multipleOfFive)
switch matches
{
case (true, true) : print("FIZZBUZZ")
case (true, false) : print("FIZZ")
case (false, true) : print("BUZZ")
case (false, false) : print(i)
}
}
Or, just eliminate the variables entirely:
for i in 1...100
{
switch (i % 3 == 0, i % 5 == 0)
{
case (true, true) : print("FIZZBUZZ")
case (true, false) : print("FIZZ")
case (false, true) : print("BUZZ")
case (false, false) : print(i)
}
}
// FIZZ BUZZ with for
for i in 1...100 {
if i % 3 == 0, i % 5 == 0 {
print("FIZZ BUZZ")
} else if i % 3 == 0{
print("FIZZ")
} else if i % 5 == 0 {
print("BUZZ")
} else {
print(i)
}
}
// FIZZ BUZZ with Switch
for i in 1...100 {
let conditions = (i % 3 == 0, i % 5 == 0)
switch conditions {
case (true, true):
print("FIZZ BUZZ")
case (true, _):
print("FIZZ")
case (_, true):
print("BUZZ")
default:
print(i)
}
}