GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Is there a down side to solving FizzBuzz with a Switch? | Challenge 3

Forums > 100 Days of SwiftUI

Hello everyone,

Was working through Challenge 3 today which goes over "FizzBuzz" and was wondering if it would be a canidate for a switch statement. I quickly learned that you can not do something like:

for i in 1...100 {
    switch i {
    case i where (i.isMultiple(of: 3) && i.isMultiple(of: 5)):
        print("\(i) | FizzBuzz")
    case i where i.isMultiple(of: 3):
        print("\(i) | Fizz")
    case i where i.isMultiple(of: 5):
        print("\(i) | Buzz")
    default:
        print(i)
    }
}

But after looking at some examples on StackOverflow it looks like you can pass multipule conditions when they are wrap in ().

for i in 1...100 {
    switch (i.isMultiple(of: 3), i.isMultiple(of: 5)) {
    case (true, true):
        print("\(i) | FizzBuzz")
    case (true, false):
        print("\(i) | Fizz")
    case (false, true):
        print("\(i) | Buzz")
    default:
        print(i)
    }
}

Does anyone know if there are any downsides to this approach instead of using if statements?

2      

The only downside that I could see is the readable. With the if and else if statements you can easily follow the logic but with the switch statement is to read what each case does you need to look at the switch (i.isMultiple(of: 3), i.isMultiple(of: 5)) line. But this is my opinion only but like the idea.

3      

I like using a variation of your second approach:

for i in 1...100 {
    switch (i % 3, i % 5) {
    case (0, 0):    // divisible by both 3 and 5
        print("Fizz Buzz")
    case (0, _):
        print("Fizz")
    case (_, 0):
        print("Buzz")
    default:
        print("\(i)")
    }
}

I don't know if the _ aka the "DGAF variable" :) saves any computation, but it's less visual clutter.

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.