Swift Package with optional dependencies?

Viewed 436

I am curious how I might set up the following:

  • Create a core Swift Package with some basic functionality.
  • Have other optional packages that dovetail with the core package (directly related). Could be 10+ function blocks of functionality.

So in a swift package, you hard-code in dependencies. I don't want that. To keep app size to a minimum and allowing developers to pick function blocks of code as they need, would one have a developer include the core package, and then other packages with specific functionality as they need - which somehow rely on the core package?

Would you just add the core swift package and then each function block swift package?

I am wondering how this could be set up to allow for flexibility for developers - keeping core function blocks separate so they would be pulled into a project as needed. Keeping things as simple as possible.

1 Answers

In a layered architecture there is typically no need for optional dependencies. In more messy dependency graphs, it can be really useful to have optional dependencies.

How to implement an optional dependency in a Swift Package?

A: Just don't add the dependency in the Package.swift file.

To use the Core package (lets call it MyCorePackage) the code will need to check if that package can be imported, like so:

#if canImport(MyCorePackage)

import MyCorePackage

#endif

struct MyRelatedType { ... }

#if canImport(MyCorePackage)

extension MyRelatedType {
  var asCoreType: CoreType { ... }
}

#endif
Related