Reputation: 389
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.
Upvotes: 4
Views: 1160
Reputation: 1266
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())
}
}
Upvotes: 4