Trait
A package trait.
Declaration
struct TraitOverview
A trait is a package feature that expresses conditional compilation and potentially optional dependencies. It is typically used to expose additional or extended API for the package.
When you define a trait on a package, the package manager uses the name of that trait as a conditional block for the package’s code. Use the conditional block to enable imports or code paths for that trait. For example, a trait with the canonical name MyTrait allows you to use the name as a conditional block:
#if MyTrait
// additional imports or APIs that MyTrait enables
#endif // MyTraitIf your conditional code requires a dependency that you want to enable only when the trait is enabled, add a conditional declaration to the target dependencies, then include the import statement within the conditional block. The following example illustrates enabling the dependency MyDependency when the trait Trait1 is enabled:
targets: [
.target(
name: "MyTarget",
dependencies: [
.product(
name: "MyAPI",
package: "MyDependency",
condition: .when(traits: ["Trait1"])
)
]
),
]Coordinate a declaration like the example above with code that imports the dependency in a conditional block:
#if Trait1
import MyAPI
#endif // Trait1