Skip to content

Instantly share code, notes, and snippets.

@chefnobody
Created March 6, 2018 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chefnobody/bb6374b12fb5a056306e7d5e6091684e to your computer and use it in GitHub Desktop.
Save chefnobody/bb6374b12fb5a056306e7d5e6091684e to your computer and use it in GitHub Desktop.
Playing with ways to do fizz-buzz in Swift.
//: Playground - noun: a place where people can play
import Foundation
func fizzable(_ num: Int) -> Bool {
return num % 3 == 0
}
func buzzable(_ num: Int) -> Bool {
return num % 5 == 0
}
func fizzBuzz(_ max: Int) -> [String] {
var results = [String]()
guard max > 0 else { return results }
for i in 0...max {
if fizzable(i) && buzzable(i) {
results.append("FizzBuzz")
} else if fizzable(i) {
results.append("Fizz")
} else if buzzable(i) {
results.append("Buzz")
} else {
results.append(String(describing: i))
}
}
return results
}
fizzBuzz(100)
.forEach { print($0) }
var results = [Int]()
.map { i -> String in
if fizzable(i) && buzzable(i) {
return "FizzBuzz"
} else if fizzable(i) {
return "Fizz"
} else if buzzable(i) {
return "Buzz"
} else {
return String(describing: i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment