Here's my approach to an extensible version of the FizzBuzz challenge in Swift (so one can add more numbers to be checked against other than just 3
and 5
).
I initially tried using dictionaries but since they don't necessarily preserve the order of elements it could lead to BuzzFizz
return values.
I personally think that, while the program does work as expected, it isn't clear how it works. I mean, it's not as readable as I'd like it to be for doing such a simple task.
How can I improve it?
func fizzBuzz (n: Int, responsesByMultiples: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]) -> String {
var result: String = ""
for key in responsesByMultiples {
let (multiple, response) = key,
isMultiple: Bool = (n % multiple) == 0
if isMultiple {
result += response
}
}
return result == "" ? String(n) : result
}
for i in 1...100 {
print(fizzBuzz(n: i))
}