Last active
March 2, 2023 12:52
-
-
Save kbazzani/1fd278235e335938f43cd81137029414 to your computer and use it in GitHub Desktop.
A swift dependency injection example using a variable property and generics
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
| import Foundation | |
| protocol SomeProtocol<Thing> | |
| { | |
| associatedtype Thing | |
| func doSomething() | |
| } | |
| struct SomeStruct<Thing>:SomeProtocol | |
| { | |
| let thing:Thing | |
| func doSomething() | |
| { | |
| print( "=> \(thing)" ) | |
| } | |
| } | |
| struct SomeClass | |
| { | |
| var someThing:any SomeProtocol | |
| func run() | |
| { | |
| self.someThing.doSomething() | |
| } | |
| } | |
| let someStructInstance1 = SomeStruct(thing:"What is the answer to the ultimate question?") | |
| let someStructInstance2 = SomeStruct(thing:42) | |
| let someStructInstance3 = SomeStruct(thing:someStructInstance1) | |
| let someStructInstance4 = SomeStruct(thing:someStructInstance2) | |
| let someStructInstance5 = SomeStruct(thing:[someStructInstance1,someStructInstance2,someStructInstance3,someStructInstance4]) | |
| var someClassInstance = SomeClass( someThing:someStructInstance1 ) | |
| someClassInstance.run() | |
| someClassInstance.someThing = someStructInstance2 | |
| someClassInstance.run() | |
| someClassInstance.someThing = someStructInstance3 | |
| someClassInstance.run() | |
| someClassInstance.someThing = someStructInstance4 | |
| someClassInstance.run() | |
| someClassInstance.someThing = someStructInstance5 | |
| someClassInstance.run() | |
| /* | |
| Output: | |
| => What is the answer to the ultimate question? | |
| => 42 | |
| => SomeStruct<String>(thing: "What is the answer to the ultimate question?") | |
| => SomeStruct<Int>(thing: 42) | |
| => [__lldb_expr_24.SomeStruct<Swift.String>(thing: "What is the answer to the ultimate question?"), __lldb_expr_24.SomeStruct<Swift.Int>(thing: 42), __lldb_expr_24.SomeStruct<__lldb_expr_24.SomeStruct<Swift.String>>(thing: __lldb_expr_24.SomeStruct<Swift.String>(thing: "What is the answer to the ultimate question?")), __lldb_expr_24.SomeStruct<__lldb_expr_24.SomeStruct<Swift.Int>>(thing: __lldb_expr_24.SomeStruct<Swift.Int>(thing: 42))] | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment