OS version availability check in @SceneBuilder

Created
Updated
TagsSwiftSwiftUI

There are times when you might need to show different root views depending on the available OS version. For example you may have a new API that can be only used in the latest OS version.

The problem with this is that body of your App structure wouldn’t allow that:

@main
struct YourApp: App {
    var body: some Scene {
        if #available macOS(13.0, *) { // Error
            ...
        } else {
            ...
        }
    }
}

The reason is that implicitly body of the App is @SceneBuilder (the same way body of the View is implicitly a @ViewBuilder) and @SceneBuilder doesn’t allow to have a version check inside it. It would be allowed in an ordinary property though, like this:

@main
struct YourApp: App {
    var body: some Scene {
        content
    }

    var content: some Scene {
        if #available macOS(13.0, *) {
            return ...
        } else {
            return ...
        }
    }
}
Note: Because it’s not a ResultBuilder anymore we got to write return every time we mean to return the view

Thanks for reading! Feel free to approach me if you have any questions or suggestions: ☎️Contact