Extract a Swift Package

A Local Package

I'm looking to extract the group of model classes into a Swift Package, no need to version and publish it seperatly from the App - so it will be a "local" package.

Xcode menu File > New > Swift Package...:

This pops up a dialogue for you to name your package.

You type in your desired name and then in the Add to: dropdown select your project name; this will most likely change the Group: dropdown to the top level.

Next we need to tell your project to include the new package. In the Navigator select the project file and for your main target's General tab look for section: Frameworks, Librarys and Embedded Content. Click the plus button (+) to pop up a dialogue with many options - use the search bar to find your new library name, select it and click Add.

Oh - that's a lot of work... and it is just the shell of the new library that we've created. Now we need to populate the library with the source code and tests. That is much easier. You should be able to drag and drop in the Navigator the files you want to move into your new library package.

You may also need to specify a minumal build platform for your package in the manifest named Package.swift:

platforms: [ .iOS(.v13) ],

Dont forget you will want to add your new library to the project's Targets in the Build Phases tab and the Link Binary With Libraries section.


Important to note - when extracting this set of files from your existing project Xcode drops these files from the Repo and does NOT create a new Repo up on your Remote Origin - so you will now need to manually do this operation.


See Also:

WWDC2019 Creating Swift Packages video

https://developer.apple.com/documentation/swift_packages/organizing_your_code_with_local_packages

If you see a message like: Swift package product <your library> is linked as a static library by <your product Test> and <your product>. This will result in duplication of library code.

You might just remove the library from your Tests and or see: https://forums.swift.org/t/adding-a-package-to-two-targets-in-one-projects-results-in-an-error/35007/9




If you are wondering ... how do I publish on the app store an app that is dynamicaly linked to a seperately distributed package... well me too?

Maybe some answers in this WWDC2020 talk: Distribute binary frameowrks as Swift packages.