UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

1      

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.

2      

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.

1      

Hacking with Swift is sponsored by RevenueCat

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

Learn more here

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

Reply to this topic…

You need to create an account or log in to reply.

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.