'How to make a SwiftUI conditional modifier works with different result types?

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?



Solution 1:[1]

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())
            }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1