Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "do nothing" in ternary operator in SwiftUI?

Tags:

swift

swiftui

This is my code:

struct GameView : View {
    @State
    private var clicked1 : Bool = false
    
    var body: some View {
        HStack {
            VStack {
                Image("shape0")
                    .overlay(clicked1 ?
                        RoundedRectangle(cornerRadius:10)
                        .stroke(Color.yellow, lineWidth: 7) : pass()
                    )
                    .onTapGesure {
                        print("Image is clicked")
                    }
            }
        }
    }
}

But some errors happen around pass().

I want to do nothing when variable clicked1 is false.

How can I fix it?

like image 462
riterlee Avatar asked Nov 02 '25 00:11

riterlee


1 Answers

.overlay expects some View type as a parameter.

If you want to use a ternary operator, it has to return the same type. For a "do nothing" view, use EmptyView(), but since it has to be the same type, one way to do this would be by wrapping each conditional view with AnyView:

Image("shape0")
   .overlay(clicked1
            ? AnyView(RoundedRectangle(cornerRadius:10)
                         .stroke(Color.yellow, lineWidth: 7))
            : AnyView(EmptyView())
           )

EDIT: Actually - Optional<Wrapped: View> also conforms to View, so this is a better approach than above - i.e. just return the view you want or nil:

Image("shape0")
   .overlay(clicked1 ? RoundedRectangle(cornerRadius:10)
                         .stroke(Color.yellow, lineWidth: 7) : nil)

Another approach would be to use computed property which returns a conditional view:

var body: some View {
   Image("shape0")
      .overlay(overlayView)
}

@ViewBuilder
var overlayView: some View {
    if clicked1 {
        RoundedRectangle(cornerRadius:10)
                         .stroke(Color.yellow, lineWidth: 7)
    }
}
like image 182
New Dev Avatar answered Nov 04 '25 14:11

New Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!