Why does this SwiftUI compile?

Hi,

We ended up releasing a bug in our apps because of a view modifier that looks like this:

func body(content: Content) -> some View {
        if #available(iOS 16.0, tvOS 16, *) {
            content
                .scrollDismissesKeyboard(.immediately)
        }
    }

Obviously, it is missing an else statement just returning content.

But how can this even compile? On iOS < 16 and tvOS < 16 it is returning VOID / NOTHING! while it must return Some View!

Replies

You probably test with iOS 16 target.

So, as #available is checked at compile time, it does return a View.

But if you test with a target below iOS 16, it will fail to compile, with error: Missing return in global function expected to return 'some View'

The same if you test the future with

        if #available(iOS 17.0, tvOS 17, *) {

Note: it may not be a good choice to name your func body…