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
forloop.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
switchto 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
forloop 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)) }