Member-only story
From Rust to Swift
How to package your native libraries written in Rust for use with Swift distribution tools. The proper way.

TL;DR
Completed sample code repository with Rust and Swift artifacts.
Our Objective
Ever wondered how you can distribute your native Rust library for use as a Swift library, specifically distribute it in such a way that it can work as a package dependency for other libraries or apps for all Apple platforms? If the answer is yes, this guide is for you.
In this article, we’ll go through the process of building a simple library written in Rust. We’ll expose its methods to Swift, compile it for all platforms and devices, and finally, package everything into a redistributable archive that can be referenced using Swift Package Manager or other distribution tools, like CocoaPods or Carthage.
Tools and Environments
In order to bake this pie, we’ll need a MacOS device with Xcode tools installed. We’ll also need the Rust toolchain to build our native libraries.
There are a few other tools and components needed, such as runtimes for different architectures, but we’ll address those as we move along.
Write a tiny Rust library
Let’s begin by creating a small library in Rust.
mkdir mathwiz && cd mathwiz
cargo init --lib
We’ll call it MathWiz and we add a couple of simple functions in the src/lib.rs
file to define our API:
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
a + b
}#[no_mangle]
pub extern "C" fn flip(a: bool) -> bool {
!a
}
The goal here is to make our Rust functions available as C-callable functions using the support in Rust for Foreign Function Interface. In practice, your methods will look a little more complex, but that’s outside the scope of this exercise.
I will be covering some good practices on how to define highly maintainable, safe, and extendable FFI contracts in another article, so stay tuned!