gpt4 book ai didi

swift - Swift 通用协议(protocol)注入(inject)可能吗?

转载 作者:可可西里 更新时间:2023-11-01 00:40:17 27 4
gpt4 key购买 nike

我正在尝试使用通用协议(protocol)并注入(inject)具体实现,但出现以下错误:Protocol 'Repo' can only be used as a generic constraint because it has Self or associated type requirements at 让 repo : repo

我的代码

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)
}
}

首先调用入口点并建立依赖树。

最佳答案

我认为您正在寻找的是这样的东西:

    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())
}
}

关于swift - Swift 通用协议(protocol)注入(inject)可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44906916/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com