Skip to content

Instantly share code, notes, and snippets.

@daltonclaybrook
Created February 24, 2017 22:25
Show Gist options
  • Select an option

  • Save daltonclaybrook/cfaf66036207ecf9d423acbd64de0d0a to your computer and use it in GitHub Desktop.

Select an option

Save daltonclaybrook/cfaf66036207ecf9d423acbd64de0d0a to your computer and use it in GitHub Desktop.
//MARK: Strategy protocol
protocol StrategyAny {
func performAny(input: Any) -> Any?
}
extension StrategyAny where Self: Strategy {
func performAny(input: Any) -> Any? {
if let input = input as? Input {
return perform(input: input)
}
return nil
}
}
protocol Strategy: StrategyAny {
associatedtype Input
associatedtype Output
func perform(input: Input) -> Output
}
//MARK: Strategy manager
class StrategyManager {
static let shared = StrategyManager()
var strategies = [String: StrategyAny]()
func register<T: Strategy>(strategy: T, for identifier: String) {
strategies[identifier] = strategy
}
func performStrategy<T, U>(for identifier: String, with input: T) -> U? {
guard let strategy = strategies[identifier] else { return nil }
return strategy.performAny(input: input) as? U
}
}
//MARK: Demo
struct FooStrategy: Strategy {
typealias Input = Double
typealias Output = String
func perform(input: Double) -> String {
return "\(input * 10)"
}
}
StrategyManager.shared.register(strategy: FooStrategy(), for: "foo")
let result: String? = StrategyManager.shared.performStrategy(for: "foo", with: 20.0)
print("\(result)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment