Skip to content

Instantly share code, notes, and snippets.

@dstaley
Last active February 5, 2019 21:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dstaley/ea6f3df2b81d69a6b7d7 to your computer and use it in GitHub Desktop.
Save dstaley/ea6f3df2b81d69a6b7d7 to your computer and use it in GitHub Desktop.
FizzBuzz in Swift using pattern matching
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))
}
@ultimapanzer
Copy link

Nice, I like the functional style.

@mgedigian
Copy link

@Westacular
Copy link

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.

@mattyohe
Copy link

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