Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a populated VStack from a SwiftUI function

Tags:

swiftui

I would like to return different views from a function, a Text or a VStack of a Text and a Button. Here's one of my attempts:

func buildResponseText2() -> some View {
    if (userData.success) {
        return VStack {
            Text("Well Done")
            Button("Play Again", action: {self.userData.reset()})
        }
    }
    return VStack {
        Text("Unlucky")
    }
}

This does not compile, I get the error

Function declares an opaque return type, but the return statements in its body do not have matching underlying types

Is there a way to return view containers like VStack with heterogeneous contents?

like image 760
dumbledad Avatar asked Jan 09 '20 10:01

dumbledad


2 Answers

Use type erasing AnyView as return type, as below

func buildResponseText2() -> AnyView {
    if (userData.success) {
        return AnyView(VStack {
            Text("Well Done")
            Button("Play Again", action: {self.userData.reset()})
        })
    }
    return AnyView(VStack {
        Text("Unlucky")
    })
}
like image 146
Asperi Avatar answered Oct 26 '22 23:10

Asperi


You were close to the solution, actually. Indeed, you can use some View as return type this way:

func buildResponseText2() -> some View {
    Group {
        if userData.success {
            VStack {
                Text("Well Done")
                Button("Play Again", action: {self.userData.reset()})
            }
        } else {
            Text("Unlucky")
        }
    }
}
like image 23
matteopuc Avatar answered Oct 26 '22 23:10

matteopuc