Conditional Modifiers *if available*

I am adopting some of the new glass UI, but having to duplicate a lot of code to maintain support for previous UI systems in macOS. An example:

            if #available(macOS 26.0, *) {
                VStack {
                    /*some 40+ lines of code clipped here for brevity*/                    
                }
                .cueButtons()
                .cueStyleGlass()
            } else {
                VStack {
                    /*identical 40+ lines of code clipped here for brevity*/
                 }
                .cueButtons()
                .cueStyle()
            }

If I try to use conditional modifiers as indicated here:

extension View {
    func cueStyle(font: Font = .system(size: 45)) -> some View {
        if #available(macOS 26.0, *) {
            modifier(GlassCueStyle(font: font))
        } else {
            modifier(CueStyle(font: font))
        }
    }
}

I get this error:

Conflicting arguments to generic parameter 'τ_1_0' ('ModifiedContent<Self, GlassCueStyle>' vs. 'ModifiedContent<Self, CueStyle>')

Is there a better way to do this?

Thanks for the post.

My apologies as is hard to follow the code as the .cueStyle() is in else? so the if #available(macOS 26.0, *) { won’t apply there as far as I can tell. Can you post the code in a better way?

There is a way I personally handle conditional modifiers in SwiftUI without duplicating large blocks of code. You can use an extension to conditionally apply the appropriate modifier based on the macOS version, while ensuring both modifiers conform to the same type.

One approach is to define a protocol that both GlassCueStyle and CueStyle conform to, and then use that protocol to write a conditional modifier.

protocol CueStyleModifier: ViewModifier {
    init(font: Font)
}

Maybe too over complicating that? Make sure both GlassCueStyle and CueStyle conform to the protocol. Create a conditional extension on View to apply the correct modifier.

extension View {
    func applyCueStyle(font: Font = .system(size: 45)) -> some View {
        #if os(macOS) && targetEnvironment(macCatalyst)
        if #available(macOS 26.0, *) {
            return self.modifier(GlassCueStyle(font: font))
        } else {
            return self.modifier(CueStyle(font: font))
        }
        #else
        return self.modifier(CueStyle(font: font))
        #endif
    }
}

This approach centralizes the logic for choosing the correct style modifier and ensures type consistency, thereby eliminating code duplication and resolving the compiler error.

Looking forward to other developer’s opinion and how they manage that.

Hope this makes sense as writing code in a textview in the forums is not good as I do not know if it compiles.

Albert Pascual
  Worldwide Developer Relations.

Conditional Modifiers *if available*
 
 
Q