Conditionally apply modifier in SwiftUI

answering my own question here - I found this on StackOverflow

func `if`<Content: View>(_ conditional: Bool, content: (Self) -> Content) -> some View {
     if conditional {
         return AnyView(content(self))
     } else {
         return AnyView(self)
     }
 }

down to a single conversion to AnyView now, and cleaner usage

struct TestView: View {
    @State var showOverlay:Bool = true
    @State var activeTap:Bool = true
    
    var body: some View {
        Text("Hello, World!")
        .if(showOverlay){
              $0.overlay(Circle().foregroundColor(.red))
        }
        .if(activeTap){
            $0.onTapGesture {
                self.showOverlay = !self.showOverlay
            }
        }
    }
}
2 Likes