How to add dependency on specific library of a package?

Let's say i have a Package that offers several libraries:

let package = Package(
    name: "Foo",
    products: [
        .library(
            name: "Bar",
            targets: ["Bar"]),
        .library(
            name: "Baz",
            targets: ["Baz"]),
    ],
    dependencies: [
    ],
    targets: [
        .target(
            name: "Bar",
        ),
        .target(
            name: "Baz",
        )
    ]
)

Is there a way for another package to add a dependency to a specific Foo.Bar or Foo.Baz instead of adding a dependency to the whole Foo package?

Something like Cocoapods' Subspecs that can be used indipendently from the full podspec both from Podfile and/or another Podspec.

When you add a dependency to a package you need to declare that dependency in two places. The first is the package dependency array - that can only specify the whole package. The second is the dependency array for each target that depends on the package you're pulling in. In that part you need to declare the product that target depends on if a package vends more that one target. E.g. vapor/Package.swift at main · vapor/vapor · GitHub

I can't remember the current state of SwiftPM but IIRC it's clever enough to only download the transitive dependencies it needs and won't build products that aren't needed.

2 Likes

One particularly annoying caveat: restrictions based on platform, Swift version, etc. are package-wide. I don’t really understand why, but they are.

You may be able to use conditional compilation and/or version-specific package manifests to work around that.

Because you don’t need to use a mono package for everything. Just make separate packages if you need it.

Terms of Service

Privacy Policy

Cookie Policy