英文:
Return view from class with protocol
问题
Iv创建了一个协议和一些使用它的类
protocol Action {
var title: String { get }
associatedtype BodyView: View
var body: BodyView { get }
}
class SomeAction: Action {
var title: String = "Test Title"
var body: some View {
Text("Test")
}
}
在我的常规视图中,现在我获得一个符合协议"Action"的类,应该调用这个类的视图。
struct ActionSheet: View {
@State var action: Any Action
var body: some View {
NavigationStack {
action.body
.navigationTitle(action.title)
}
}
}
struct ActionSheet_Previews: PreviewProvider {
static var previews: some View {
ActionSheet(action: SomeAction())
}
}
但是现在我得到了以下错误:
类型 'Any View' 无法符合 'View'。
如果我只使用"SomeView"作为类型,而不是"Any Action",它可以工作。我在这里做错了什么?
英文:
Iv created a protocol and some classes that use it
protocol Action {
var title: String { get }
associatedtype BodyView: View
var body: BodyView { get }
}
class SomeAction: Action {
var title: String = "Test Title"
var body: some View {
Text("Test")
}
}
In my normal view I now get a class that conforms to the protocol "Action" and should call the view of this class.
struct ActionSheet: View {
@State var action: any Action
var body: some View {
NavigationStack {
action.body
.navigationTitle(action.title)
}
}
}
struct ActionSheet_Previews: PreviewProvider {
static var previews: some View {
ActionSheet(action: SomeAction())
}
}
But now I get the following error:
> Type 'any View' cannot conform to 'View'
If I just use "SomeView" as a type instead of "any Action" it works. What am I doing wrong here?
答案1
得分: 1
some View
需要一个特定的、在编译时已知的具体类型,该类型符合View协议。您对any Action
的使用似乎试图绕过这一点,但是不能这样做。您需要在编译时能够证明ActionSheet.body
的返回值是特定类型。
通常情况下,可以通过使ActionSheet成为泛型来解决这个问题:
struct ActionSheet<A: Action>: View {
@State var action: A
var body: some View {
NavigationStack {
action.body
.navigationTitle(action.title)
}
}
}
英文:
some View
requires a specific, known-at-compile-time concrete type that conforms to View. Your use of any Action
seems to be trying to circumvent that. It cannot. You need to be able to prove at compile-time that the returned value of ActionSheet.body
is a particular type.
Generally this would be addressed by making ActionSheet generic:
struct ActionSheet<A: Action>: View {
@State var action: A
var body: some View {
NavigationStack {
action.body
.navigationTitle(action.title)
}
}
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论