HiveBrain v1.2.0
Get Started
← Back to all entries
patternswiftMinor

FizzBuzz in Swift 2

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
swiftfizzbuzzstackoverflow

Problem

I saw this question:
Is this FizzBuzz Swift-y? and I couldn't resist the temptation to attempt a Swift2 implementation:

for i in 1...100 {
    switch i {
    case _ where i % 15 == 0: print("FizzBuzz")
    case _ where i %  3 == 0: print("Fizz")
    case _ where i %  5 == 0: print("Buzz")
    default                 : print(String(i))
    }
}


Is this swift-y and clear enough? Can you suggest any improvement?

Solution

I would have started by looking over more than just the question in the linked question. You should have looked at the answers.

First of all, while the added where clause option in switch statements is a nice addition to the language, it doesn't make anything better here.

Moreover, we're failing on the single-responsibility-principle by not extracting out a method which takes an Int and returns a String and then simply looping over calls to this function.

So, the answer to this question is effectively going to be an a rewrite of the accepted answer of the linked question:

func fizzBuzzify(value: Int) -> String {
    switch (value % 3, value % 5) {
    case (0,0): return "FizzBuzz"
    case (0,_): return "Fizz"
    case (_,0): return "Buzz"
    default: return String(value)
    }
}

func fizzBuzz(startingValue: Int = 1, endingValue: Int = 100) {
    for i in startingValue...endingValue {
        print(fizzBuzzify(i))
    }
}


Then you get it all done in a single line:

fizzBuzz()

Code Snippets

func fizzBuzzify(value: Int) -> String {
    switch (value % 3, value % 5) {
    case (0,0): return "FizzBuzz"
    case (0,_): return "Fizz"
    case (_,0): return "Buzz"
    default: return String(value)
    }
}

func fizzBuzz(startingValue: Int = 1, endingValue: Int = 100) {
    for i in startingValue...endingValue {
        print(fizzBuzzify(i))
    }
}

Context

StackExchange Code Review Q#102191, answer score: 9

Revisions (0)

No revisions yet.