Opaque result type question

Use the @ViewBuilder If/Else:

@ViewBuilder
func screenBuilder(_ screen : Screen) -> some View {
    if screen == .homepage: {
        HomePage()
    } else {
        Text("Not Implemented")
    }
}

You can keep adding else if to handle any number of "cases".

Unfortunately the Swift compiler in Xcode 11.3.1 is a little buggy now and the above code may not conpile. See I'm stumped with this @ViewBuilder on var body: some View compile error: Cannot convert return expression of type '_ConditionalContent<Text, Text>' to return type 'some View'

You can get around the bug by first create an variable and use that in the If/Else:

let homePage = HomePage()    // <== work around the bug
let text = Text("Not Implemented")
@ViewBuilder
func screenBuilder(_ screen : Screen) -> some View {
    if screen == .homepage: {
        homePage               // <== use this instead
    } else {
        text
    }
}
1 Like