When trying to use a generic type to init/add a view to another SwiftUI view, I get the error Type 'T' has no member 'init'
. How can this be solved?
I guess the problem is, that View
is just a protocol which only requires a body
property and nothing more. But what type could be used instead?
Simple Example:
Trying to use TrippleView<T: View>
which should create/show three views of type T
. Adding views (RedRectView
or BlueCircleView
) is no problem. Passing these views as generic parameter fails:
struct SomeView: View {
var body: some View {
TrippleView<RedRectView>()
TrippleView<BlueCircleView>()
}
}
struct TrippleView<T: View>: View {
var body: some View {
VStack {
// Does NOT work: Type 'T' has no member 'init'
T()
T()
T()
// Works fine
// RedRectView()
// BlueCircleView()
// RedRectView()
}
}
}
struct RedRectView: View {...}
struct BlueCircleView: View {...}
EDIT:
The TrippleView
is of course just an example. I would like to use the generic view just as any other generic type: To a common base "type" in different scenarios.
For example two versions of a list view which use a generic CellView
to display the same data in two different styles / layouts.