[英]Type 'any View' cannot conform to 'View' on protocol with generics
I'm using a protocol to define an override to the default View
protocol to create some templated views in my app.我正在使用协议来定义对默认
View
协议的覆盖,以在我的应用程序中创建一些模板化视图。 They will all share the same CalculationComponent
view for the bulk of the layout but then will implement different buttons / controls that are passed through with a @ViewBuilder
which uses generics.对于大部分布局,它们都将共享相同的
CalculationComponent
视图,但随后将实现不同的按钮/控件,这些按钮/控件通过使用泛型的@ViewBuilder
传递。
The issue I'm having is that when defining my protocol body, the generic type is throwing an error where Type 'any View' cannot conform to 'View'
.我遇到的问题是,在定义我的协议主体时,泛型类型会引发错误,其中
Type 'any View' cannot conform to 'View'
。 I think this has directly to do with the <Content: View>
part on CalculationComponent
我认为这与
CalculationComponent
上的<Content: View>
部分直接有关
CalculationComponent.swift计算组件.swift
struct CalculationComponent<Content: View>: View {
@Binding var mainCalculation: String
@Binding var secondaryCalculation: String
@ViewBuilder var content: () -> Content
var body: some View {
// Template UI here
content()
}
}
CalculationView.swift CalculationView.swift
protocol CalculationView: View {
var mainCalculation: String { get set }
var secondaryCalculation: String { get set}
var body: CalculationComponent<View> { get } // Type 'any View' cannot conform to 'View'
}
CalculatorView.swift CalculatorView.swift
struct CalculatorView: CalculationView {
@State internal var mainCalculation: String = ""
@State internal var secondaryCalculation: String = ""
var body: CalculationComponent {
CalculationComponent(
mainCalculation: $mainCalculation,
secondaryCalculation: $secondaryCalculation
) {
Text("Buttons and view content here")
}
}
}
If I understand correctly, you want a specialised version of the View
protocol, where Body
is CalculationComponent<some View>
, and you don't want to write explicitly what " some View
" is when conforming to the protocol, plus some other requirements.如果我理解正确,您需要
View
协议的专用版本,其中Body
是CalculationComponent<some View>
,并且您不想明确写出符合协议时的“ some View
”是什么,以及其他一些要求。
You can add an associated type to CalculationView
,您可以将关联类型添加到
CalculationView
,
protocol CalculationView: View {
associatedtype Content: View
var mainCalculation: String { get set }
var secondaryCalculation: String { get set}
var body: CalculationComponent<Content> { get } // Type 'any View' cannot conform to 'View'
}
and then say CalculationComponent<some View>
when conforming to the protocol:然后在符合协议时说
CalculationComponent<some View>
:
struct CropFactorCalculatorView: CalculationView {
@State internal var mainCalculation: String = ""
@State internal var secondaryCalculation: String = ""
var body: CalculationComponent<some View> {
CalculationComponent(
mainCalculation: $mainCalculation,
secondaryCalculation: $secondaryCalculation
) {
VStack {
Text("Some Text")
Text("Some Other Text")
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.