Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is Swift generic protocol injection possible?

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.

like image 724
archLucifer Avatar asked Nov 08 '25 04:11

archLucifer


1 Answers

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())
      }
    }
like image 197
jwswart Avatar answered Nov 11 '25 17:11

jwswart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!