So, trying to learn Swift. Not really a web language, so probably not going to be the easiest way to try my web kata. But thanks to the fairly amazing playgrounds, FizzBuzz is pretty easy. I'm still not so great on the test front, but you can see the output in the sidebar, so issue gracefully dodged! Right? Right.
Anyway, Swift looks a bit like Ruby, so we can do it in a Ruby way, right? Right.
func fizzbuzz(number:Int) -> String {
if (divisibleByFifteen(number)) {return "FizzBuzz"}
if (divisibleByThree(number)) {return "Fizz"}
if (divisibleByFive(number)) {return "Buzz"}
return "\(number)"
}
func divisibleByThree(number:Int) -> Bool {
return number % 3 == 0
}
func divisibleByFive(number:Int) -> Bool {
return number % 5 == 0
}
func divisibleByFifteen(number:Int) -> Bool {
return number % 15 == 0
}
fizzbuzz(1) #=> 1
fizzbuzz(2) #=> 2
fizzbuzz(3) #=> Fizz
fizzbuzz(4) #=> 4
fizzbuzz(5) #=> Buzz
fizzbuzz(6) #=> Fizz
fizzbuzz(7) #=> FizzBuzz
Nice and easy. Everything is strongly typed (the main function could return AnyObject, but String is neater and it meant I got to play with string interpolation, which is always fun, right? Right). Still, mostly pretty familiar.
But, Swift also has more functional stuff, so we can do the (slightly silly) things we did with Javascript. Curried functions!
func divisibleBy(divisor:Int)(number:Int) -> Bool {
return number % divisor == 0
}
let divisibleByThree = divisibleBy(3)
let divisibleByFive = divisibleBy(5)
let divisibleByFifteen = divisibleBy(15)
...
if (divisibleByThree(number: number)) {return "Fizz"}
...
(1...100).map(fizzBuzz)
Nice. Slight irritation that you seem to need the parameter name in the final call, but happy enough.
Also fun, Swift playgrounds let you know how many times a function gets called. So I now know there are six numbers divisible by fifteen in the range 1 to 100, fourteen divisible by five, 27 divisible by three and 53 indivisible by any of the above. Also, the divisibleBy constructor gets called 261 times. Which may not be the most efficient way to do things, but it is slightly fun.
There's probably a better way, though, right? Right. Thank you for being so agreeable today. So, I Googled Swift FizzBuzz and the first results all looked roughly like this:
func fizzbuzz(i: Int) -> String {
let result = (i % 3, i % 5)
switch result {
case (0, _):
return "Fizz"
case (_, 0):
return "Buzz"
case (0, 0):
return "FizzBuzz"
default:
return "\(i)"
}
}
Which, hey, some pattern matching I guess, but there's something about a switch statement that's slightly underwhelming to me. But that's probably just becuase I'm unfamiliar with coding styles that aren't covered by a particular twelve-week intensive coding course... Always more to learn.