【发布时间】:2022-02-03 23:45:44
【问题描述】:
来自 java/kotlin 背景,我试图了解具有相关类型的 swift 协议。为什么下面的sn-p编译失败,报错:“Type ViewFactoryImpl does not conform to protocol ViewFactory”,怎么解决?
protocol ViewFactory {
associatedtype V: View
func createSomeView() -> V
func createAnotherView() -> V
}
class ViewFactoryImpl: ViewFactory {
func createSomeView() -> some View {
return ViewA()
}
func createAnotherView() -> some View {
return ViewB()
}
}
通过玩耍,我能够通过定义以下内容来编译
protocol ViewFactory {
associatedtype V1: View
associatedtype V2: View
func createSomeView() -> V1
func createAnotherView() -> V2
}
我不明白这个问题。我认为关联类型是为整个协议定义的,可以在多种方法中使用。我错过了什么?
【问题讨论】:
标签: swift protocols associated-types