How to return a button from a function WITH modifiers in SwiftUI?

Viewed 364

So I have a make button function that I'm calling in a ForEach loop in my content view...here it is:

func makeButton(info: Info) -> some View {
    guard let variable = value else { return
        Button(action: {
            print("printing now...")
        }, label: {
            Text("Label")
        })
    }
    return Button(action: {
        //execute a function here
    }, label: {
        Text("Other Label")
            .padding(.vertical, 20)
            .frame(width: UIScreen.main.bounds.width * 0.8)
            .background(Color.white)

    })
}

I get an error statement on the first line that says: 'Function declares an opaque return type, but the return statements in its body do not have matching underlying types.' I guess this is because the Text on one possible return has modifiers and the other doesn't, or maybe it has to do with the action code blocks, but I'm not sure how to go about making this function error-free. I need the guard statement in there, and I'd also really like to put modifiers on the label of the button at the end of the function. Any help much appreciated!

1 Answers

Swift/SwiftUI is picky with the syntax of these things.

To return different types and still conform to some View, you have to use @ViewBuilder. Using @ViewBuilder also means that you use implicit returns, so the structure will be slightly different (no guard let):

@ViewBuilder func makeButton() -> some View {
        if let variable = value {
            Button(action: {
                //execute a function here
            }, label: {
                Text("Other Label")
                    .padding(.vertical, 20)
                    .frame(width: UIScreen.main.bounds.width * 0.8)
                    .background(Color.white)

            })
        } else {
            Button(action: {
                print("printing now...")
            }, label: {
                Text("Label")
            })
        }
    }
Related