Warnings as Errors for libraries/frameworks

When making a library/framework, it's often useful to be extra careful about things and want to enable treating warnings as errors. However, the only way I currently see to do this is to use the "unsafeFlags()" option:

swiftSettings: [
    .unsafeFlags(["-warnings-as-errors"],
]),

However, doing so results in restrictions on how one can depend on the library, getting errors like "error build: The package product 'MyCoolErrorFreeLibrary' cannot be used as a dependency of this target because it uses unsafe build flags." when not in a trusted context. (Override for "unsafeFlags" in Swift Package Manager?)

Does anyone know of a workaround for this? I'm looking for a way to enable the flag when building in a trusted context (i.e. building the package directly or referencing by path, etc.), but not define the flag when building in an untrusted context (i.e. when an app is depending on my framework). I'm also okay if the solution is Xcode-specific (but still keeping the library as an SPM project).

It seems SPM could use one of the following:

  • an enumeration for safe flags such as this one
  • the ability to enable unsafeFlags only when in a trusted build context

Thanks!

You do not actually want debugging or validation flags in the manifest, since clients will suffer for it too. Since you really only want them toggled at the top level, they are best expressed in the build invocation instead. That way you can be stricter during development and in continuous integration to ensure your standard, but looser with the actual release so as not to hamstring its compatibility with future compilers.

swift package --help
[...]
OPTIONS:
[...]
-Xswiftc <Xswiftc>      Pass flag through to all Swift compiler invocations
swift build -Xswiftc -warnings-as-errors

In the future you will be spared interference from dependencies.

1 Like