Sharing constants across SwiftPM

I want to use a constant in both the Package.swift file and the actual source files. It’s been asked at least once, but nothing came from that. Is it possible now?

1 Like

You can't have multiple source files contribute to the output of Package.swift, because SwiftPM uses the checksum of that file to determine whether the package changed.

So if this is possible, you'd need to do something like

  • add ../../Package.swift as a source file (is that legal? it might not be…)
  • add a custom define to your target's build settings, like BUILDING_MY_LIBRARY
  • use #if within Package.swift to exclude the actual package definition when BUILDING_MY_LIBRARY is set, eg:
let importantConstant = 42

#if !BUILDING_MY_LIBRARY
import PackageDescription

Package(
    ...
)
#endif

Sounds like traits from Swift 6.1 could help you.