Conditional Imports

Hi - have been out of the game for a while, and am having trouble figuring out if this is feasible now -

Can a package conditionally import dependencies only if a user of the package has already imported that dependency?

EG; let's say I have a package that by itself does not rely on Foundation, so I don't want to import it. However, I'd like to include additional functions if Foundation is already imported elsewhere, without requiring a build of the package to automatically link to Foundation.

Is the only alternative for something like this along the lines of SwiftNIO having a "NIOFoundationCompat" target?


The feature you're looking for is cross-import overlays, but it's only been pitched and not officially supported* yet.

* The compiler supports it for system frameworks, but since it hasn't gone through Swift Evolution yet, its implementation is subject to change and it doesn't work with Swift Package Manager.

1 Like

Interesting - that might be an answer, though from a brief glance it seems like it's solving a more complicated set of conditions?

Just wish there was a more straightforward method - eg something like this, particularly for system libraries so you could explicitly prevent them from being linked automatically. Wouldn't actually be source-breaking as far as I can tell and would allow more granular control over how packages link against system libraries in addition to external packages, and would probably make #if canImport behave more like (I suspect) most people expect it to when used.

/// in Package.swift
dependencies: [.optionalPackage(name: "Foundation")],
targets: [.target(name: "MyLib", optionalDependencies: ["Foundation"])

/// MyLib.swift
#if canImport("Foundation") 
import Foundation