Created
November 4, 2019 04:06
-
-
Save fmo91/8c4b62bef951c528ec4983d97968bfdd to your computer and use it in GitHub Desktop.
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
// We create a protocol for formatting a name | |
protocol NameFormatterType { | |
func format(name: String) -> String | |
} | |
// A concrete implementation adds a prefix "Sir" to the given name. | |
struct SirFormatter: NameFormatterType { | |
func format(name: String) -> String { | |
"Sir \(name)" | |
} | |
} | |
// We will register that implementation | |
Dependencies.Container.default.register(SirFormatter()) | |
// Apart from that, we have a Person struct. | |
struct Person { | |
// We INJECT the NameFormatterType dependency using our handy annotation. | |
@Dependencies.Inject() private var formatter: NameFormatterType | |
let name: String | |
// And in any part of the struct code we can use the injected dependency | |
func present() { | |
print("Hi, I am \(formatter.format(name: name))") | |
} | |
} | |
let fernando = Person(name: "Fernando") | |
fernando.present() // Will print: "Hi, I am Sir Fernando" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment