Is there a way to enforce that no code from a library target can be public?

Test targets are nice in that it doesn't matter if the code you put in them gets accidentally annotated as public, because test targets don't get included in a library. But what if you have a target that has to get included in a library, where you want to disallow any public API. Is there anything to enforce that?


Use case: Test targets don't support SwiftUI previews. As far as I understand, previews require being included as a non-test target in a library, to work.


The Previews directory here is an example of what I'm talking about. I figure if you've got an entire relevant directory, maybe there's something to be done? I've never heard of it if so.

// swift-tools-version: 6.1

import PackageDescription

_ = Package(
  name: name(),
  platforms: [.iOS(.v15), .macOS(.v12)],
  products: [
    .library(
      name: name(),
      targets: [name(), name(suffix: .previews)]
    )
  ],
  targets: [
    .target(name: name(), path: "Sources"),
    .target(
      name: name(suffix: .previews),
      dependencies: [dependency],
      path: .previews
    ),
    .testTarget(name: name(suffix: "Tests"), dependencies: [dependency])
  ]
)

func name(suffix: String? = nil) -> String {
  "MyLibrary" + (suffix ?? "")
}
extension String {
  static var previews: Self { "Previews" }
}
var dependency: Target.Dependency { .init(stringLiteral: name()) }
1 Like

Would Periphery's Redundant Public Accessibility be good enough for a post-write analysis?

1 Like