Last active
February 5, 2019 21:19
-
-
Save dstaley/ea6f3df2b81d69a6b7d7 to your computer and use it in GitHub Desktop.
FizzBuzz in Swift using pattern matching
This file contains 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
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)" | |
} | |
} | |
for number in 1...100 { | |
println(fizzbuzz(number)) | |
} |
Reminds me of scala http://rosettacode.org/wiki/FizzBuzz#Idiomatic_scala_code
Actually, the idiomatic Scala version's pattern matching works in Swift practically unchanged:
func fizzbuzz(i: Int) -> String {
switch (i % 3, i % 5) {
case (0, 0):
return "FizzBuzz"
case (0, _):
return "Fizz"
case (_, 0):
return "Buzz"
default:
return "\(i)"
}
}
Also, while Swift's Range
doesn't come with a foreach
method like Scala's, it's easy enough to define one as an extension:
extension Range {
func foreach(f: T -> ()) -> () {
for x in self {
f(x)
}
}
}
(1...100).foreach({
println(fizzbuzz($0))
})
Really, the only thing missing from Swift that's present in the Scala version is Scala's implicit return values for all code blocks.
Just as a note... dstaley's answer is incorrect.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, I like the functional style.