Created
March 6, 2018 15:52
-
-
Save chefnobody/bb6374b12fb5a056306e7d5e6091684e to your computer and use it in GitHub Desktop.
Playing with ways to do fizz-buzz in Swift.
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
//: 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