Conditional target linked despite package trait not being enabled

Hello,

I'm running into what looks like incorrect behavior in Swift Package Manager's support for package traits (as introduced in SE-0450).

Setup

I have a Swift package structured like this:

  • BackendA: imports Foundation
  • BackendB: does not import Foundation
  • Main: conditionally depends on either BackendA or BackendB

The package defines these traits:

traits: [
  "UseBackendA",
  "UseBackendB",
  .default(enabledTraits: ["UseBackendA"])
]

And Main conditionally links:

.target(
  name: "Main",
  dependencies: [
    .target(name: "BackendA", condition: .when(traits: ["UseBackendA"])),
    .target(name: "BackendB", condition: .when(traits: ["UseBackendB"]))
  ]
)

Problem

In a consumer package, I set:

.package(url: "...", traits: ["UseBackendB"])

However, when building the package and inspecting the binary (ldd, nm, etc.), it still links Foundation, even though:

  • BackendB does not import Foundation
  • BackendA is not used

This was tested in a clean swift-latest Docker container to rule out host SDK contamination.

Questions

  • Could this be a bug or is this known?
  • Should .target(condition: .when(traits: ...)) completely exclude the target from being built and linked?

If needed, I can share a minimal example package that reproduces this.

Thanks in advance!

2 Likes

Hi Philipp,

Thank you for posting about this issue! This is indeed a bug - trait-guarded target dependencies should be excluded from linking.

I tried replicating this locally on the release/6.1 branch for swift-package-manager and was able to yield the same results as you've described here - although, when testing this on the main branch it seems this issue has been fixed!

For future releases of Swift I believe this will no longer be an issue, but I'll keep an eye out for it and will create a GitHub issue linking to this post to include some tests so that we can track the behaviour. :slight_smile:

1 Like

Following up: here is the GitHub issue that will track the inclusion of tests!

1 Like

Very much appreciated.

1 Like

I just re-ran my script with the 6.2 nightly docker image and can also confirm it is fixed. Thank you for investigating.

1 Like