从类中返回视图,使用协议。

huangapple go评论72阅读模式
英文:

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&lt;A: Action&gt;: View {
    @State var action: A
    
    var body: some View {
        NavigationStack {
            action.body

            .navigationTitle(action.title)
        }
    }
}


</details>



huangapple
  • 本文由 发表于 2023年6月30日 02:42:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定