Skip to content

Instantly share code, notes, and snippets.

@fmo91
Created November 4, 2019 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmo91/8c4b62bef951c528ec4983d97968bfdd to your computer and use it in GitHub Desktop.
Save fmo91/8c4b62bef951c528ec4983d97968bfdd to your computer and use it in GitHub Desktop.
// 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