In a Package.swift manifest with tools version 6.1, how do package traits make a dependency optional, and how does a client choose which traits it gets?
answer
- optional, additive features
- a compilation condition per trait
- conditional product dependency
- listing traits drops the defaults
basics
~20 sA package declares traits in Package(traits:), sets defaults with .default(enabledTraits:), links an optional product under condition: .when(traits:) and guards code with #if. A client lists traits on its .package dependency; any list replaces the defaults unless it includes .defaults.
solid answer
~40 sTraits, from tools version 6.1, are named optional features of a package. The manifest declares them in `Package(traits:)` with `.trait(name:description:enabledTraits:)` and names the ones on by default with `.default(enabledTraits:)`. An optional dependency is declared normally, then attached to a target with `.product(name: "RemoteLog", package: "Logging", condition: .when(traits: ["RemoteLogging"]))`, and the code guards both the import and its use with `#if RemoteLogging`. A client with no `traits:` gets the defaults; `traits: ["RemoteLogging"]` gives only that trait, so the defaults must be listed again with `.defaults`. Traits are additive and unified across the build graph, the manifest cannot express mutually exclusive traits, and `swift package show-traits` lists what a package offers.
code
swift · 29 lines// swift-tools-version: 6.1
import PackageDescription
let package = Package(
name: "ClientKit",
products: [
.library(name: "Networking", targets: ["Networking"]),
],
traits: [
.trait(name: "RemoteLogging", description: "Send request logs to the remote logger"),
.trait(name: "Metrics"),
.default(enabledTraits: ["Metrics"]),
],
dependencies: [
.package(path: "../Logging"),
],
targets: [
.target(
name: "Networking",
dependencies: [
.product(
name: "RemoteLog",
package: "Logging",
condition: .when(traits: ["RemoteLogging"])
),
]
),
]
)go deeper
Recall that traits are optional features of a package, introduced with tools version 6.1, and that code checks them with #if.
Explain how a trait declaration, a .when(traits:) product dependency and #if guards work together, and how .default(enabledTraits:) sets the starting point.
Catch the defaults trap in client manifests, design traits as additive, and build the trait-off combination so unguarded imports cannot ship.
Judge when an optional dependency deserves a trait instead of a separate library product, given that traits unify across the whole graph.
## What a trait is Before Swift 6.1, each version of a package offered one fixed API surface. From tools version 6.1, a package can declare **traits**: named, optional features that switch on extra API and, with it, extra dependencies. Inside the package that defines it, an enabled trait becomes a compilation condition, so code writes `#if RemoteLogging`. Trait names are namespaced to their package, so two packages can both define `Metrics`; `default` and `defaults`, in any capitalisation, are reserved. ## Declaring traits Traits go in the `traits:` parameter of `Package`, which sits between `products:` and `dependencies:` in the 6.1 initializer: - `.trait(name:description:enabledTraits:)` declares one, and a plain string literal such as `"Metrics"` is shorthand for a trait with only a name; - `enabledTraits:` lets one trait switch on others, which groups features; - `.default(enabledTraits: ["Metrics"])` names the traits that are on when a client asks for nothing; with no default declared, SwiftPM enables no traits by default. ## Making a dependency optional In the scenario, the networking library should pull in a remote-logging package only for apps that want it: 1. Declare the logging package in `dependencies:` as usual. 2. Attach its product to the target with `condition: .when(traits: ["RemoteLogging"])`. 3. Guard both the `import RemoteLog` and the code that calls it with `#if RemoteLogging`. With the trait off, the product is not a dependency of the target and the guarded code is not compiled; an import left unguarded is what breaks the trait-off build. Build settings can be tied to a trait the same way, with `.when(traits:)` on a setting's condition. ## How a client chooses | Client's dependency declaration | Traits enabled in ClientKit | |---|---| | `.package(path: "../Kit")` | the defaults (`Metrics`) | | `.package(path: "../Kit", traits: ["RemoteLogging"])` | only `RemoteLogging` | | `.package(path: "../Kit", traits: [.defaults, "RemoteLogging"])` | `Metrics` and `RemoteLogging` | The middle row is the trap the documentation calls out: once a client lists traits, it defines the whole set, and the defaults are not added automatically. The same `traits:` parameter exists on URL-based dependencies such as `.package(url:from:traits:)`. A trait requested for a dependency can itself be conditional, `.trait(name: "X", condition: .when(traits: ["Y"]))`, so it is on only when the client package has its own trait `Y` enabled. ## Rules that shape the design - **Additive and unified.** SwiftPM treats traits as purely additive and unifies enabled traits across every package in the build graph, so if two packages enable different traits of one dependency, it builds with all of them. - **No mutual exclusion in the manifest.** When two traits truly cannot coexist, guard it in code with `#if FeatureA && FeatureC` and `#error`. - **Add, never remove.** The documentation says enabling a trait should not remove or disable public API; changing the default set is a major version change if it removes API, while adding traits is not. - **Command-line traits stay local.** Traits enabled when building a package activate only within that package; to enable a dependency's trait, the manifest must say so. ## Trait or separate library product? Traits are not the only way to make functionality optional. A package can instead vend a second library product, say `NetworkingRemoteLog`, that depends on the logging package, and let each client target opt in by depending on it. The two choices behave differently: | | Trait | Separate library product | |---|---|---| | Who opts in | a package, in its dependency declaration | a target, in its dependency list | | Scope | unified across the whole build graph | only the targets that depend on the product | | API shape | adds API to existing modules behind `#if` | a separate module the client imports | | Tools version | 6.1 or later | any | A trait fits when the optional feature has to change code inside existing modules, such as an extra code path in the client's request pipeline. A separate product fits when the optional piece can live in its own module, because then nothing is unified behind anyone's back. ## Trying it locally 1. `swift package show-traits`, added in SwiftPM 6.3, lists a package's traits, marks the defaults and shows descriptions. 2. `swift build --traits RemoteLogging` builds with that trait; `--enable-all-traits` and `--disable-default-traits` cover the extremes. 3. Build the meaningful combinations in CI, because the trait-off build is the one that catches an unguarded import.
- Two packages in one graph enable different traits of the same dependency; what does the dependency build with?Both sets. SwiftPM treats traits as additive and unifies the enabled traits across all packages in the build graph, so the dependency is built once with the union. That is why a trait must only add API: no client can rely on a trait being off.
- How do you stop two traits from being enabled together?The manifest cannot declare mutually exclusive traits. The documented approach is a guard in code, `#if FeatureA && FeatureC` with an `#error` inside, which fails the build with a clear message when a client enables both.
- Listing one trait on a dependency adds it on top of the dependency's default traits.
- A trait can switch a dependency between two mutually exclusive implementations in the manifest.
- Traits are a good way to hide or replace existing public API for some clients.
- Passing --traits when building an app also turns those traits on in its dependencies.
- Trait names are global, so two packages cannot both define a Metrics trait.
Assumes tools version 6.1 or later, which added Package(traits:), Trait and .when(traits:) conditions; show-traits arrived in SwiftPM 6.3; behaviour checked with SwiftPM 6.4.