Skip to content

Instantly share code, notes, and snippets.

@ncipollo
Last active September 17, 2023 12:42
Show Gist options
  • Save ncipollo/6b642be6e29b8e38c25b20da718b0efd to your computer and use it in GitHub Desktop.
Save ncipollo/6b642be6e29b8e38c25b20da718b0efd to your computer and use it in GitHub Desktop.
Injectable
struct Injector {
func inject() -> String {
"testing 123" // simplified inject function
}
}
protocol Injectable {
static func inject(_ injector: Injector) -> Self
}
struct MyStruct: Injectable {
let value: String
static func inject(_ injector: Injector) -> Self {
Self(value: injector.inject())
}
}
let injector = Injector()
func get<T>() -> T? {
let type = T.self
if type is Injectable.Type {
return (type as! Injectable.Type).inject(injector) as? T
}
// Would normally throw instead of returning nil
return nil
}
let myStruct: MyStruct? = get()
let myInt: Int? = get()
print("my struct: \(myStruct?.value ?? "")")
print("int: \(myInt ?? 0)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment