Created
March 18, 2019 07:18
-
-
Save halleygen/8a9a0993855d8b1371ee1da009c5d49b to your computer and use it in GitHub Desktop.
Fizz Buzz in Swift
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
| protocol Fizzable { | |
| func canBeFizzed() -> Bool | |
| } | |
| protocol Buzzable { | |
| func canBeBuzzed() -> Bool | |
| } | |
| protocol Fizzbuzzable: Fizzable, Buzzable { | |
| func canBeFizzBuzzed() -> Bool | |
| } | |
| extension Fizzbuzzable { | |
| func canBeFizzBuzzed() -> Bool { | |
| return canBeBuzzed() && canBeFizzed() | |
| } | |
| } | |
| extension Int: Fizzbuzzable { | |
| func canBeFizzed() -> Bool { | |
| return self % 3 == 0 | |
| } | |
| func canBeBuzzed() -> Bool { | |
| return self % 5 == 0 | |
| } | |
| } | |
| protocol Factory { | |
| func makeString() -> String | |
| } | |
| struct FizzFactory: Factory { | |
| func makeString() -> String { | |
| return "fizz" | |
| } | |
| } | |
| struct BuzzFactory: Factory { | |
| func makeString() -> String { | |
| return "buzz" | |
| } | |
| } | |
| struct FizzBuzzFactory: Factory { | |
| private let fizzFactory = FizzFactory() | |
| private let buzzFactory = BuzzFactory() | |
| func makeString() -> String { | |
| return fizzFactory.makeString() + buzzFactory.makeString() | |
| } | |
| } | |
| struct IntFactory: Factory { | |
| let intValue: Int | |
| func makeString() -> String { | |
| return "\(intValue)" | |
| } | |
| } | |
| // This is where the magic happens | |
| func fizzbuzz(_ range: ClosedRange<Int> = 0 ... 100) { | |
| for i in range { | |
| let factory: Factory | |
| if i.canBeFizzBuzzed() { | |
| factory = FizzBuzzFactory() | |
| } else if i.canBeFizzed() { | |
| factory = FizzFactory() | |
| } else if i.canBeBuzzed() { | |
| factory = BuzzFactory() | |
| } else { | |
| factory = IntFactory(intValue: i) | |
| } | |
| print(factory.makeString()) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment