Last active
August 29, 2015 14:04
-
-
Save rpomeroy/f806be1d23dc62c87737 to your computer and use it in GitHub Desktop.
FizzBuzz in Swift (Playground)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// FizzBuzz problem in Swift (Playground) | |
import Foundation | |
println("\n\nClassic imperative - Print Fizz or Buzz or FizzBuzz") | |
for i in 1...100 { | |
var output = "" | |
if i % 3 == 0 {output += "Fizz"} | |
if i % 5 == 0 {output += "Buzz"} | |
print((output == "" ? "\(i)" : output) + ", ") | |
} | |
println("\n\nSwifty functional foo style -- transforming an Range[Int] to a String") | |
println((1...100).map({ea -> String in | |
if ea % 15 == 0 {return "FizzBuzz"}; | |
if ea % 3 == 0 {return "Fizz"}; | |
if ea % 5 == 0 {return "Buzz"}; | |
return "\(ea)" | |
})) | |
println("\n\n...and using pattern matching (wish it was more Scala-like syntax") | |
println((1...100).map({ea -> String in | |
switch (ea % 3, ea % 5, ea % 15) { | |
case (0,0,0): return "FizzBuzz" | |
case (0,_,_): return "Fizz" | |
case (_,0,_): return "Buzz" | |
case (_,_,_): return "\(ea)" | |
}})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment