Skip to main content
1 of 4
syb0rg
  • 21.9k
  • 10
  • 113
  • 193

Is this FizzBuzz Swift-y?

Kinda, but it could be a lot better. Here's what I would do to fix it:

  • Extrapolate this code into a method, then call the method from the for loop.

     func fizzbuzz(i: Int) -> String
     {
        // ...
     }
    
  • There is a handy Swift feature called "Tuples". Tuples are groupings of values. We can use them to represent our results from the modulo operation.

     let result = (i % 3, i % 5)
    
  • Now that we are using a Tuple to represent the result, we can easily use a switch to perform the necessary actions.

     switch result
     {
         case (0, _):
             return "Fizz"
         case (_, 0):
             return "Buzz"
         case (0, 0):
             return "FizzBuzz"
         default:
             return "\(i)"
     }
    

You might be wondering what that underscore is. That _ is used to indicate a discarded value that we don't really care about, the value in the tuple that doesn't really matter to us in the evaluation.

  • Your for loop isn't very "Swift-y". Here's how I would write is so that it calls the function 100 times.

     for number in 1...100
     {
         println(fizzbuzz(number))
     }
    
syb0rg
  • 21.9k
  • 10
  • 113
  • 193