NOTE: this question is not asking for help solving FizzBuzz. Please don't post answers that just solve FizzBuzz. Answers to this question should relate to matching multiple true switch
cases
Consider an attempted FizzBuzz solution in Swift using a switch statement:
func fizzBuzz(forInt int: Int) -> String {
var output = ""
switch 0 {
case (int % 3): output += "Fizz"
case (int % 5): output += "Buzz"
default:
output = String(int)
}
return output
}
// FAILS
assert(fizzBuzz(forInt: 15) == "FizzBuzz", "15 should output `FizzBuzz`, not `Fizz`!")
The correct output on iteration 15
should be "FizzBuzz"
because 15 is divisible by both 3 and 5.
But the program above outputs "Fizz"
because only the first passing case
is executed.
The Swift docs state:
A switch statement executes an appropriate block of code based on the first pattern that matches successfully.
It seems that it would be useful for there to be a similar, switch
-like statement that matches any true case rather than just the first.
Pattern matching patterns can currently be used in the following situations:
You use these patterns in a case label of a switch statement, a catch clause of a do statement, or in the case condition of an if, while, guard, or for-in statement.
Matching multiple patterns seems impossible in Swift. Options considered:
fallthrough
Switch fallthrough
allows one executed case to fall into and execute the physically next case, but without actually testing the case statement. It does not allow multiple, arbitrary, unordered cases to be executed only if matching.
multiple if
statements
Multiple if
statements produce the desired behavior, but are annoying for the same reasons switch
is often preferred over if-else
blocks.
if (i % 3 == 0) {
// ...
}
if (i % 5 == 0) {
// ...
}
Namely re-stating the variable being tested in each case, no compiler protection that we're evaluating the same single variable against multiple cases, etc.
tuples, etc.
Yes, it's possible to do things like switch on a tuple to produce the correct output value. But that involves duplicating code inside the cases.
switch (i % 3, i % 5) {
case (0, 0):
output += "FizzBuzz"
case (0, _):
output += "Fizz"
case (_, 0):
output += "Buzz"
The goal of this question is to have only 2 cases for "Fizz" and "Buzz". Combined execution of the true cases should produce "FizzBuzz", not a separate 3rd case that duplicates the strings.
Related:
Switch to match multiple cases from OptionSetType
Question:
Does there exist a switch
-like pattern matching control flow statement that matches any and all true cases? If not in Swift, do any languages contain such a feature?