How does Swift prevent SwiftUI `body: Never` properties from being called?

We can use @_spi to omit a declaration from a .swiftinterface file. No magic build step needed.

I put the following into MyView.swift:

import SwiftUI

public struct MyView: View {
    @_spi(Private)
    public var body: Never { fatalError() }
}

Then I compiled it as follows, based on the “Directly invoking the compiler” instructions found here:

swiftc MyView.swift -module-name MyLib -emit-module -emit-library -emit-module-interface -enable-library-evolution

The compiler writes MyLib.swiftinterface as follows, omitting the body declaration:

// swift-interface-format-version: 1.0
// swift-compiler-version: Apple Swift version 5.7 (swiftlang-5.7.0.123.7 clang-1400.0.29.50)
// swift-module-flags: -target arm64-apple-macosx12.0 -enable-objc-interop -enable-library-evolution -module-name MyLib
import Swift
import SwiftUI
import _Concurrency
import _StringProcessing
public struct MyView : SwiftUI.View {
  public typealias Body = Swift.Never
}

And it writes MyLib.private.swiftinterface as follows, containing the body declaration:

// swift-interface-format-version: 1.0
// swift-compiler-version: Apple Swift version 5.7 (swiftlang-5.7.0.123.7 clang-1400.0.29.50)
// swift-module-flags: -target arm64-apple-macosx12.0 -enable-objc-interop -enable-library-evolution -module-name MyLib
import Swift
import SwiftUI
import _Concurrency
import _StringProcessing
public struct MyView : SwiftUI.View {
  @_spi(Private) @_Concurrency.MainActor(unsafe) public var body: Swift.Never {
    get
  }
  public typealias Body = Swift.Never
}
10 Likes