Sharing Helper Code Between Package.swift Files

At one time I used the strategy of putting it all in an external tool. The manifest would have a generated portion marked at its beginning and end by some reliably unique commented token. The tool would find them and replace everything in between with the latest state of the utility code. You still have to check the generated code into source control, but at least you are only defining it in one place. These days, I would probably implement the tool as a command plugin.

For the sake of any human readers, I prefer as much as possible to keep the basic, uncluttered package declaration at the top. I then apply any repetitive aspects algorithmically in retroactive steps at the bottom. (See the post linked below.) Hence I would advise, where possible, dumping the utility code in between, so that it doesn’t displace legible information but is still available in time for any algorithms to use.


Your initial example contains this:

#if os(macOS) || os(iOS)

#if should only be used in a manifest as a workaround if the intended effect is otherwise impossible. Generally you should aim instead to use condition: .when(platforms: [...]). Using #if switches based on the host that is loading the manifest, whereas .when(platforms:) switches based on the target platform for which you are building. The latter keeps a consistent package definition with a nuanced build, whereas the former creates a different package depending on where the manifest is loaded, which can create havoc for pins, break cross‐compilation and cause other related problems.

1 Like