How can I use the Swift Collections package with a compile-time flag?

I want to try out a new type that uses the secret sorted collections from the Swift Collection library. I get errors that “SortedSet cannot be found in scope.” I just tweaked the Package.swift that was initially generated. I guess I messed up referencing the package with a different compile-time flag.

let package = Package(
  name: "XXX",
  products: [
    // Products define the executables and libraries a package produces,
    // making them visible to other packages.
    .library(
      name: "XXX",
      targets: ["XXX"]
    )
  ],
  dependencies: [
    .package(
      url: "https://github.com/apple/swift-collections.git",
      .upToNextMajor(from: "1.3.0")
    )
  ],
  targets: [
    // Targets are the basic building blocks of a package,
    // defining a module or a test suite.
    // Targets can depend on other targets in this package and
    // products from dependencies.
    .target(
      name: "XXX",
      dependencies: [
        .product(name: "Collections", package: "swift-collections")
      ],
      swiftSettings: [
        // Gain access to the in-beta "SortedSet" collection type.
        .define("COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS")
      ]
    ),
    .testTarget(
      name: "XXXTests",
      dependencies: ["XXX"]
    ),
  ]
)

I can substitute the always-available Deque type just fine.

The compilation conditions you set at target level only affect the building of Swift files that are part of the target (XXX) in question. You should be looking into package traits instead, which may set select conditions in your package dependencies.

…But it looks like swift-collections isn’t quite ready for it yet; see what’s commented out here: swift-collections/Package.swift at ec3fef18992a1ffdf89f3babc88c6a1a5c8d3c7b · apple/swift-collections · GitHub

1 Like

As of swift-collections 1.4.0+, we have a UnstableSortedCollections package trait that can be used to turn on the sorted collection types.

Beware that these types aren't finished yet, and I expect we'll have to make source breaking changes when/if we finalize their API. There may also be logic bugs hiding in there. (If you find any problems, please file issues! PRs fixing them would also be very welcome.)

3 Likes