Skip to content

Instantly share code, notes, and snippets.

@kbazzani
Last active March 2, 2023 12:52
Show Gist options
  • Select an option

  • Save kbazzani/1fd278235e335938f43cd81137029414 to your computer and use it in GitHub Desktop.

Select an option

Save kbazzani/1fd278235e335938f43cd81137029414 to your computer and use it in GitHub Desktop.
A swift dependency injection example using a variable property and generics
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