Home > Enterprise >  How to make a SwiftUI conditional modifier works with different result types?
How to make a SwiftUI conditional modifier works with different result types?

Time:02-22

This code...

Text("Hello, world!")
    .background(.regularMaterial, in: condition ? RoundedRectangle(cornerRadius: 6) : Circle())

...causes this issue:

Result values in '? :' expression have mismatching types 'RoundedRectangle' and 'Circle'

Is there a way to solve it without using the if/else syntax?

CodePudding user response:

Or if you want to definitely stick with ternary:

   Text("Hello, world!")
        .padding()
        .background(
            ZStack {
                RoundedRectangle(cornerRadius: 6)
                    .fill(.regularMaterial)
                    .opacity(condition ? 1 :0)
                Circle()
                    .fill(.regularMaterial)
                    .opacity(condition ? 0 :1)
            }
        )

CodePudding user response:

you could try using the following approach using an extension View from

https://matteo-puccinelli.medium.com/conditionally-apply-modifiers-in-swiftui-51c1cf7f61d1

extension View {
    @ViewBuilder
    func ifCondition<TrueContent: View, FalseContent: View>(_ condition: Bool, then trueContent: (Self) -> TrueContent, else falseContent: (Self) -> FalseContent) -> some View {
        if condition {
            trueContent(self)
        } else {
            falseContent(self)
        }
    }
}

struct ContentView: View {
    @State var condition = false
    
    var body: some View {
        Text("Hello, world").padding(20)
            .ifCondition(condition) { text in
                text.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 6))
            } else: { text in
                text.background(.regularMaterial, in: Circle())
            }
    }
}
  • Related