Last active
July 9, 2019 22:49
-
-
Save onmyway133/3244cde1eaf8f2cd2ecb to your computer and use it in GitHub Desktop.
SimpleResolver.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
protocol Suit { | |
var name: String { get } | |
} | |
struct AntManSuit: Suit { | |
let name: String | |
} | |
struct YellowJacketSuit: Suit { | |
let name: String | |
} | |
struct HankPym { | |
let suit: Suit | |
func fight() { | |
print("Fighting with the suit named " + suit.name) | |
} | |
} | |
class SimpleResolver { | |
var factories = [String: Any]() | |
func factory<T>(factory: () -> T) { | |
let key = String(T.self) | |
factories[key] = factory | |
} | |
func resolve<T>() -> T { | |
let key = String(T.self) | |
if let factory = factories[key] as? () -> T { | |
return factory() | |
} else { | |
fatalError("Registration not found") | |
} | |
} | |
} | |
let resolver = SimpleResolver() | |
resolver.factory { | |
YellowJacketSuit(name: "YellowJacket IS #009") as Suit | |
} | |
let suit = resolver.resolve() as Suit | |
print(suit.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment