4

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?

pawello2222
  • 46,897
  • 22
  • 145
  • 209
riterlee
  • 43
  • 4

2 Answers2

6

.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)
    }
}
New Dev
  • 48,427
  • 12
  • 87
  • 129
2

This would also work, the trick is to use Group.

Using ternary:

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

Using if:

Image("shape0")
   .overlay(
       Group {
           if clicked1 { 
               RoundedRectangle(cornerRadius:10)
                   .stroke(Color.yellow, lineWidth: 7)
           }
       }
   )
Kai Zheng
  • 6,640
  • 7
  • 43
  • 66
  • This reminded me that `Optional : View` - i.e. an optional view is a view, so no need for `Group` – New Dev Nov 14 '20 at 17:27