[英]How to add a SwiftUI some View Type as a Requirement to an Protocol?
Context语境
I have a Protocol
and would like it to have a SwiftUI
some View
Type
as one of its Requirements
.我有一个
Protocol
,并希望它有一个SwiftUI
some View
Type
作为其Requirements
之一。 I do know, that it is probably not the most elegant solution to mix the Model
with the View
, however, switching through all the different conforming Types
each time I want to use the View
isn't beautiful either.我知道,将
Model
与View
混合可能不是最优雅的解决方案,但是,每次我想使用View
时切换所有不同的符合Types
也不是很漂亮。 Even though, I ran into a problem while implementing and got the following Compiler Error
:尽管如此,我在实现时遇到了问题并得到了以下
Compiler Error
:
'some' type cannot be the return type of a protocol requirement;
'some' 类型不能是协议要求的返回类型; did you mean to add an associated type?
您是要添加关联类型吗?
Code代码
protocol Component {
var row: some View { get } // -> Compiler Error thrown in this Line.
}
// There are actually many more Types conforming to Component.
enum ComponentA: Component {
var row: some View {
Text("Component A")
}
}
struct ComponentsView: View {
var body: some View {
ForEach(components) { component in
component.row
}
}
}
Question问题
How can I achieve my goal of only having to define the selection of the appropriate SwiftUI View once?如何实现我的目标,即只需定义一次选择合适的 SwiftUI 视图?
You could follow the same technique that Apple uses for View
itself, which you can see by Command-clicking on a View
reference in Xcode and selecting Jump to Definition .您可以遵循 Apple 用于
View
本身的相同技术,您可以通过 Command-单击 Xcode 中的View
引用并选择Jump to Definition来查看。
protocol Component {
associatedtype Body: View
var row: Body { get }
As you declare some object's conformance to Component
, the row
autocomplete will automatically fill to some View
:当您声明某些对象与
Component
的一致性时, row
自动完成将自动填充到some View
:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.