How do views like EmptyView conform to the View protocol?

You're actually correct, the view is indeed "optimised" away. Example:

struct MyView: View {
  var body: some View { <-- Same here as well
    EmptyView() <-- Put a breakpoint here, its not triggered
  }
}
1 Like

Never is just an enum with no cases. So there's nothing special about how switches over Never are treated. You can get the same like this:

enum Nothing {}

func deal(with nothing: Nothing) -> String {
  switch nothing {
    // this code is correct, as it has a valid return path from every case
  }
}

Sure but the compiler knows that it's an uninhabited type and allows you to do nothing. So if you expect to return such a type why do you need to do anything since an uninhabited type can't be instantiated.

It feels like var never: Never { } should just work.

2 Likes

It should in recent compilers.

1 Like

Hmm it doesn't work with the compiler that ships with Xcode 11 beta 2:

var never: Never { } // Computed property must have accessors specified
var never: Never {
  get { } // Function with uninhabited return type 'Never' is missing call to another never-returning function on all paths
}

Tried with a development snapshot as well (slightly old), no luck.

Sorry, I was confusing this with the case where you get a Never value as an argument. If you function returns Never, it still has to do something to stop somehow, like fatalError.

2 Likes

Is that what SwiftUI views are doing (e.g. EmptyView)? I can't think of anything else (maybe infinite loop/recursion), but obviously that will cause a crash, rather than let SwiftUI ignore the body.

SwiftUI would have to be doing something at a higher level to avoid invoking the body, since if it did, it would be impossible to continue executing.

Hmm I guess so, I don't think its simply checking the type of the body property, because otherwise this should work and render nothing on the screen:

struct Empty: View {
  var body: Never { fatalError() }
}

There's something deeper going on, but it's hard to tell without doing some sort of reverse engineering.

SwiftUI knows about it’s own primitive views that return Never and does not need to call body on them. It only needs to use other data contained by the primitive views. It doesn’t know anything about your custom views so it needs to access their body. It’s turtles all the way down until a primitive is reached.

1 Like

I don't know what they're doing here, but it definitely requires special case behavior. It wouldn't fall out compositionally. Arguably, it's a bug. EmptyView could just as easily return itself from body or something like that.

2 Likes