【发布时间】:2022-12-03 03:39:56
【问题描述】:
我正在使用 Playground,Swift 5.7.1 版。
我有两个协议和两个类。第一个很简单并且有效:
protocol TestSomeB: ObservableObject {
associatedtype V: View
func returnSome() -> V
}
class TestSomeBImp: TestSomeB {
init() {}
func returnSome() -> some View {
Text("Hello World")
}
}
let testSomeBImp = TestSomeBImp()
testSomeBImp.returnSome()
这有效并给了我价值{{SwiftUI.AnyTextStorage, {key "Hello World", hasFormatting false, []}, nil, nil}}
即使基本代码结构相同,第二个也不起作用:
struct TestModel {
var title: String
}
struct TestView: View {
var body: some View {
Text("Hello, World!")
}
}
// similar to protocol TestSomeB
protocol TestSomeA: ObservableObject {
associatedtype V: View
func linkBuilder<Content: View>(data: TestModel, @ViewBuilder content: () -> Content) -> V
}
class TestSomeAImp: TestSomeA {
init() {}
// returns `some View` similar to returnSome() method above
func linkBuilder<Content: View>(data: TestModel, @ViewBuilder content: () -> Content) -> some View {
NavigationLink(destination: routeToPage(data: data)) {
content()
}
}
private func routeToPage(data: TestModel) -> some View {
TestView()
}
}
let testSomeImp = TestSomeAImp()
testSomeImp.linkBuilder(
data: TestModel(title: "Hello "),
content: {
Text("World!")
}
)
可悲的是,这给了我错误:protocol requires nested type 'V'; do you want to add it? associatedtype V: View
- 我需要返回
some View,但我还需要抽象我的实现。 - 我尝试在返回类型中使用
Content而不是V但这也给我错误。 - 我尝试在协议中仅使用
associatedtype V而不指定类型,但这也给了我一个错误。 - 我尝试创建两个关联类型,一个 V,另一个用于 Content,但是这实际上给了我相同的
nested错误 - 我尝试添加
typealias V,但由于它是嵌套的,错误不断出现。
请指教。谢谢!
【问题讨论】:
标签: ios swift generics swift-playground