'Why primitive View in SwiftUI has no body?

The View protocol requires a body property:

public protocol View {
    associatedtype Body : View

    @ViewBuilder var body: Self.Body { get }
}

Why have some built-in Views in SwiftUI no body?

@frozen public struct EmptyView : View {
    @inlinable public init()

    public typealias Body = Never
}
@frozen public struct VStack<Content> : View where Content : View {
    @inlinable public init(alignment: HorizontalAlignment = .center, spacing: CGFloat? = nil, @ViewBuilder content: () -> Content)

    public typealias Body = Never
}

have no body at all..

let emptyView = EmptyView().body
// Value of type 'EmptyView' has no member 'body'

let vStackView = VStack { Text("some text")}.body
// Value of type 'VStack<Text>' has no member 'body'

How are these Views implemented?



Solution 1:[1]

I'm not an expert but this seems very logical. Imagine that no views are offered by SwiftUI and you want to create the very first view. This view has the computed property body that is expecting you to a return a type that conforms to the View protocol (i.e. should have the body property). This will go forever. Hence, there has to be a View without the body property.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ayman Elakwah