How to make part of a library optional?

Hi all,

I'm working with a library that under Linux has a very useful feature, but it requires the user to install a package in order to compile.

Can I make that part of the library optional? I would like it to be included by default, but let the user optionally omit it. Can this be done?

1 Like

Since Package.swift is written in Swift, can't you import the additional package conditionally, using #if os(Linux) and/or an environment variable?

1 Like

That could work. Can I query for environment variables at compile time?

A quick test says yes. I was able to use values from the ProcessInfo.processInfo.environment dictionary in my manifest.

1 Like

:thinking: that works for not importing the package.

But how would I change the API? I was thinking of marking the class that uses that package as unavailable if the user decides to omit it. Or maybe not compiling it at all, with a big #if, which would be less clean but would work. For that though, I need to know if the user used that env. variable from an #if directive.

If you conditionally imported a package, the new #if canImport(ThatPackage) is probably the cleanest solution?

1 Like