How do some SwiftUI views hide their body property at compile-time?

It's more of a question about Swift than SwiftUI.

Consider a view like Text, which conforms to View.

let body = Text("...").body // Value of type 'Text' has no member 'body'

Yet, Text conforms to View, so the following is possible:

func doSomething<T: View>(_ view: T) {
   let body = view.body

I understand that Text, VStack , EmptyView, etc.. have the body property type of Never, so the above function will fail at run-time, but that still doesn't explain (to me, at least) why .body is inaccessible at compile-time.

What's the behind-the-scenes Swift magic here?


I'm no expert, but I imagine it has something to do with the compiler knowing that Text.body is of type Never, whereas it does not in the case of a generic View.

1 Like

I thought so too, but then how could one recreate it? For example, the following compiles

struct Foo: View {
    var body: Never { fatalError() }
let body = Foo().body // this compiles
1 Like

The "magic" is not in the language, per se, but in how Apple has designed the SwiftUI framework, and fiddled with the type system to make the magic work. Property wrappers, opaque return types are parts of the solution, but, how ViewBuilders and other parts of SwiftUI use these capabilities of the language is part of the Apple-private frameworks. You might take a look at OpenSwiftUI (I think that's what it's called) as folks are trying to reverse-engineer SwiftUI.

Just a guess, but I have a suspicion it uses the underscored @_implements attribute.

1 Like