Last active
September 17, 2023 12:42
-
-
Save ncipollo/6b642be6e29b8e38c25b20da718b0efd to your computer and use it in GitHub Desktop.
Injectable
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
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