Is it possible to enable a trait for a target within the same package

Let's say i have a module A that depends on Module B in the same package, and B has a trait that is optionally enabled. Can A add B as a dependency with the trait enabled, just for A?

1 Like

Thanks for this interesting traits question!

Generally, traits are enabled on a package-wide basis; namely, say if a package Foo has traits FooTrait, BarTrait declared like so in its Package.swift:

let package = Package(
    name: "Foo",
    products: [
       // ...
    ],
    traits: [
        "FooTrait",
        "BarTrait"
    ],
// ... etc.

and I run something like this on the command line:

swift build --traits FooTrait

Then package Foo's graph will operate with the knowledge that FooTrait is enabled. Within the targets defined in Foo, you can conditionally depend on other products or modules by using:

// ... other package definition stuff
    targets: [
        .target(
            name: "ModuleA",
            dependencies: [
                .target(
                    name: "ModuleB",
                    // conditional usage of dependency ModuleB *only* 
                    // if FooTrait is enabled for this package.
                    condition: .when(traits: ["FooTrait"]))
            ]
        ),
        .target(
            name: "ModuleB",
        )
    ]
// ... etc.

If I ran the above command against this package with this manifest, then ModuleA would be able to depend on and use ModuleB in its source.

There isn't currently a mechanism for intra-module enablement of traits, but I would love to know more about your use case; do you have an example package manifest you could share?

Additionally, if you're looking for more information on traits there are some official docs that go more into detail here :slight_smile: