I wrote this code to solve the problem of needing to switch between HStack and VStack in SwiftUI:
struct HorVStack<Content: View>: View {
let needVertical: Bool
let content: Content
init(needVertical: Bool, @ViewBuilder content: () -> Content) {
self.needVertical = needVertical
self.content = content()
}
var body: some View {
if needVertical {
return AnyView(VStack { content })
} else {
return AnyView(HStack { content })
}
}
}
This works fine. What I don't understand is why I have to erase the type, even though each return type conforms to View? I feel like there's an interesting lesson regarding the underlying mechanics that I'm missing. Can anyone fill me in?