How to include a Core ML model in a Swift Package

Niklas Büchner
Published in
2 min readFeb 28, 2021

--

When I started creating my first ever machine learning app, I decided to use CoreML instead of Tensorflow or PyTorch just because of the convenience. Not only was I able to understand the training a lot better, but also the deployment: Just throw it into Xcode and use the class which is created for the model. That’s it.

However, factoring out your code and model into a library — a Swift Package — removes the convenience of dragging and dropping the model into Xcode. Xcode can’t handle this for some reason… 🤷 So what do we need to do?

1.) Compiling the model yourself

When you add the .mlmodel file into your Swift Package nothing will happen. You will need to compile the model yourself. This can be done with the coremlcompiler which Xcode bundles with its command line tools. This will create a my-model.mlmodelc directory.

Important: The created artifact must be located in your Sources/MyPackageName folder since you will not be able to include it into your package otherwise.

2.) Add it as a resource to your library

Unfortunately the compiler is not smart enough to include your model right away. You’ll also need to add the resources into your Package.swift. This should be in your targets > your-target >resources as shown below:

Important: Firstly, you need to add the resource to every target individually. Secondly, the path in copy is relative to your Sources/MyPackageName source root folder.

That’s all. 👍

Good luck with your project. 🚀

--

--