how to declare a variable that will later be defined as a SwiftUI view?

I can refactor, to avoid having to do this, but what can I use as the var type in the snippet below:


var mySwiftUIView: __________?
if shouldUseFancyView() {
    mySwiftUIView = FancyView(param: paramValue)
} else {
    mySwiftUIView = PlainView(param: otherParamValue)
}
let hostingView = NSHostingView(rootView: mySwiftUIView)


In the API, NSHostingView's rootView appears to be of type Content, but it's not clear to me what Content refers to.


thanks in advance,


Mike

Answered by OOPer in 422015022

I can refactor, to avoid having to do this

Then you should better refactor.


But if you really need it, you can write something like this.

        var mySwiftUIView: AnyView
        if shouldUseFancyView() {
            mySwiftUIView = AnyView(FancyView(param: paramValue))
        } else {
            mySwiftUIView = AnyView(PlainView(param: otherParamValue))
        }
        let hostingView = NSHostingView(rootView: mySwiftUIView)


Your second case:

        var hostingView: NSView
        if shouldUseFancyView() {
            hostingView = NSHostingView(rootView: FancyView(param: paramValue))
        } else {
            hostingView = NSHostingView(rootView: PlainView(param: otherParamValue))
        }

alternatively/additionally, if I instead want to declare a hostingView var, what type would it use?


var hostingView: NSHostingView<_____: _____>?

if shouldUseFancyView() {

hostingView = NSHostingView(rootView: FancyView(param: paramValue))

} else {

hostingView = NSHostingView(rootView: mySwiftUIView = PlainView(param: otherParamValue))

}

Accepted Answer

I can refactor, to avoid having to do this

Then you should better refactor.


But if you really need it, you can write something like this.

        var mySwiftUIView: AnyView
        if shouldUseFancyView() {
            mySwiftUIView = AnyView(FancyView(param: paramValue))
        } else {
            mySwiftUIView = AnyView(PlainView(param: otherParamValue))
        }
        let hostingView = NSHostingView(rootView: mySwiftUIView)


Your second case:

        var hostingView: NSView
        if shouldUseFancyView() {
            hostingView = NSHostingView(rootView: FancyView(param: paramValue))
        } else {
            hostingView = NSHostingView(rootView: PlainView(param: otherParamValue))
        }
how to declare a variable that will later be defined as a SwiftUI view?
 
 
Q