I am trying to use generic protocols and inject a concrete implementation but I get the following error: Protocol 'Repo' can only be used as a generic constraint because it has Self or associated type requirements at let repo: Repo
My code
protocol Repo{
associatedtype T
func doSomething() -> T
}
class MyRepo: Repo{
func doSomething() -> String{
return "hi"
}
}
class SomeClass {
let repo: Repo
init(repo: Repo) {
self.repo = repo
repo.doSomething()
}
}
class EntryPoint{
let someClass: SomeClass
init(){
someClass = SomeClass(repo: MyRepo)
}
}
Entry point is called first and sets up the dependency tree.
I think what you are looking for is something like this:
protocol Repo {
associatedtype T
func doSomething() -> T
}
class MyRepo: Repo{
func doSomething() -> String{
return "hi"
}
}
class SomeClass<A: Repo> {
let repo: A
init(repo: A) {
self.repo = repo
_ = repo.doSomething()
}
}
class EntryPoint{
let someClass: SomeClass<MyRepo>
init(){
someClass = SomeClass<MyRepo>(repo: MyRepo())
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With