I'm doing this problem set "FizzBuzz", and my switch statement is giving me some problems, here's my code:
func fizzBuzz(n: Int) -> String {
switch n {
case n % 3 == 0: print("Fizz")
case n % 5 == 0: print("Buzz")
case n % 15 == 0:print("FizzBuzz")
}
return "\(n)"
}
If you could provide me with pointers / hints, instead of giving me the correct code, that would be swell :D I'd prefer solving it myself, but a few hints could get me out of this hole.
Try using "case let where":
A bit late, but just to add to the various answers. I believe the elegant solution to use now is this:
Swift can switch on tuples (sorta structs, but constructed on the fly without a definition somewhere else in the code). Then in the case labels you can check for multiple values at once, which is ideal for FizzBuzz!
To break it down a bit, this part
generates a tuple with two boolean values. Then a case label like this
checks if both these values (essentially
n%3==0
andn%5==0
) are true and prints "FizzBuzz"Doing it like this makes it very easily expandable. You can add a third definition to the switch argument and a third true/false to your cases and your FizzBuzz can become a FizzBuzzJazz. You can also name the values in the tuple if you want by simply adding labels like
making the code more readable in some cases.
Just two things wrong:
(1) Your cases are boolean expressions, so you want to compare them against
true
, notn
;(2) You need a default case. So:
I know its little late for this answer. I am updating the answer of @Leo Dabus with an another approach which is written and tested on Xcode 7.3.1 and Swift 2.2.
Thanks, Hope this helped.