4 ms·
I assume your goal with [0] is to be able to say `ViewContainer()` and have it wrap an `EmptyView`? You can do that like the following: class ViewContainer<V
by lilyball 7y ago
I assume your goal with [0] is to be able to say `ViewContainer()` and have it wrap an `EmptyView`? You can do that like the following:
class ViewContainer<ViewType: View> {
var view: ViewType
init(view: ViewType) {
self.view = view
}
}
extension ViewContainer where ViewType == EmptyView {
convenience init() {
self.init(view: EmptyView())
}
}
With this code, writing `ViewContainer()` will produce a `ViewContainer<EmptyView>`. Writing `ViewContainer<Text>()` will fail with an error (as expected).
Note that since this is statically-typed, the following will fail:
let container = ViewContainer()
container.view = Text("wat")
If you want to be able to do that, you'd have to write something like
let container = ViewContainer(view: AnyView(EmptyView()))
container.view = AnyView(Text("wat"))
- Razengan 7y agoI love the extension idea, noting that for later. :) But I do need to be able to change the view during runtime, so I settled on just type-erasing to AnyView for now.
- lilyball 7y agoIf you have a set number of possible view types you could in theory have it hold onto an enum of the different types.
- deleted 7y ago[deleted]