假设我有以下符合View
的协议:
protocol Foo: View {
init(field: Binding<Bool>)
}
然后,我有两个符合该协议的 struct :
struct BarView: Foo {
@Binding private var field: Bool
init(field: Binding<Bool>) {
self._field = field
}
var body: some View {
Text(field ? "Some text" : "Some other text")
}
}
struct QuxView: Foo {
@Binding private var field: Bool
init(field: Binding<Bool>) {
self._field = field
}
var body: some View {
Text(field ? "Some text" : "Some other text")
}
}
现在,在我的主要视图中,我有一个符合Foo
的类型集合.当我try 初始化这些类型之一的视图时,我得到错误Type 'any Foo' cannot conform to 'View'
.我怎么才能避免这种情况?
struct MainView: View {
static let fooViews: [any Foo.Type] = [
BarView.self,
QuxView.self
]
@State private var field = false
var body: some View {
if let fooView = MainView.fooViews.first {
fooView.init(field: $field)
}
}
}
谢谢! (请记住,这只是我试图解决的问题的一个最小例子)