Home > Software design >  Conditionally include macOS-only code in a SwiftUI (Mac Catalyst) project?
Conditionally include macOS-only code in a SwiftUI (Mac Catalyst) project?

Time:11-16

I am writing an app that runs on both iOS and macOS, using Mac Catalyst with Swift.

I want to set a property that is only available on macOS but I cannot find a way using #available or @available to prevent the compiler from including this line of code in the iOS builds:

This syntax does not work because the mandatory trailing * includes all iOS versions.

if #available(macCatalyst 13.0, *) {
    view.showsZoomControls = true
}

I tried adding a nonsense version of iOS using iOS 999 but that didn't work either, because the property is marked strictly unavailable in iOS.

Using @available there's a longhand syntax using introduced: that allows per-OS versions to be specified and requires a separate @available entry per OS but I can't see any way to use that. It seems you can't use @available on a block of code.

Is there really no sane way to do this?

For reference, the definition of this specific property is:

@property (nonatomic) BOOL showsZoomControls
    API_AVAILABLE(macos(10.9), macCatalyst(13.0)) 
    API_UNAVAILABLE(ios, watchos, tvos);

CodePudding user response:

Crisis averted - it seems that available is the wrong hammer for this nail.

What's working for me now is the much simpler:

#if os(macOS)
view.showsZoomControls = true
#endif

CodePudding user response:

You can identify/restrict Mac Catalyst with target environment

#if targetEnvironment(macCatalyst)
view.showsZoomControls = true
#endif
  • Related