Skip to content
Tutorials Center
My learning

Topics

Lesson 125 of 146 ยท Platforms and Ecosystem

Embedded Swift

Learn what Embedded Swift is, how it differs from regular Swift, what it leaves out, and how to design firmware-style code with generics, typed throws and fixed-size storage. Runnable simulations included.

A phone has gigabytes of memory and an operating system that loads shared libraries on demand. A small microcontroller, the chip inside a thermostat, a smart light or a sensor tag, may have 64 kilobytes of memory in total, no operating system, no heap you can count on, and no room for a language runtime. For decades that world belonged to C and C++, with assembly underneath. Embedded Swift is the effort to let Swift go there too: the same language, compiled into very small, self-contained programs for such chips.

This lesson explains what Embedded Swift is, what it takes away from the Swift you know, and how you write code that suits it. The compiler for microcontrollers, the board and the flashing tools cannot run in this browser, so the build and hardware parts are read-only examples and clearly labelled. The design techniques, however, are ordinary Swift, and the runnable examples simulate the hardware so that you can try them here. They are written in the style that Embedded Swift requires: generics instead of existential types, typed throws, wrapping arithmetic and fixed-size storage.

Embedded Swift is a young and fast-moving part of the language. Details such as the exact compiler flags, the list of supported chips and the status of individual features change between releases. Treat the build commands below as an illustration of the shape of the workflow, and check the current Swift release notes and the official Embedded Swift examples before starting a real project.

What Embedded Swift is

Normal Swift programs carry a runtime: a library that provides type metadata for reflection, dynamic casts, protocol witness tables for existential values, reference counting, memory allocation and a lot of unicode data for strings. Together that is several megabytes. Embedded Swift is a compilation mode that removes the runtime's dependence on this machinery. Instead of discovering types while running, the compiler works out everything at build time, specializes every generic function for the exact types used, and throws away what is unused. The output is plain machine code that looks like what a C compiler would produce, often a few kilobytes for a small program.

Key facts:

  • It is the same language. Structs, enums, classes, optionals, closures, generics, protocols, operators, if and switch expressions and even typed throws work as usual. What is restricted is mostly things that need the full runtime.
  • It targets microcontrollers such as ARM Cortex-M chips (found in many boards from Raspberry Pi, STMicroelectronics and Nordic), some RISC-V chips and other small targets, plus WebAssembly. You can also compile in this mode for a desktop computer, which is handy for testing.
  • It is enabled by a compiler setting rather than by a different language. In current Swift 6 releases that is the experimental feature named Embedded, together with whole-module optimization.
  • There is no operating system assumed. Your program is the only code running. You write what happens at start-up and talk to hardware directly.

Why use Swift for this

C is small and fast, but it makes it easy to write buffer overflows, use-after-free bugs and forgotten initialization, and on a device that runs unattended for years, memory errors are expensive. Swift gives you:

  • Memory safety by default: bounds-checked arrays and integer overflow checks, no uninitialized variables, no dangling pointers in safe code.
  • Strong types: an enum for a state machine, a distinct type for each register or unit, and exhaustive switch that tells you when you forgot a state.
  • Zero-cost abstractions: generics are specialized away completely, so a protocol-based hardware abstraction layer compiles into the same instructions as hand-written code.
  • One language across the stack: the parsing and business logic of a gadget can be shared with its phone app and its server.

You also take on the costs: a smaller ecosystem of chip support code than C, and a toolchain that is still maturing.

What you give up

Embedded mode removes features that depend on a dynamic runtime or a large library. The list below describes the idea; the compiler tells you the details with diagnostics when you use something that is not allowed.

Not available (or very limited) Why What to use instead
Existential types of ordinary protocols (any Sensor) Needs runtime tables and metadata Generics: func read<S: Sensor>(_ s: S)
Untyped throws and any Error The thrown value is an existential Typed throws: throws(SensorError)
Reflection (Mirror, String(describing:)) Needs full type metadata Write formatting code by hand
Codable, JSON, Foundation Depends on reflection and a large library Parse bytes yourself
Heavy Unicode string processing Large data tables Work with UInt8 bytes or keep strings simple
Dynamic features (casting to protocols, Any) Runtime type information Enums with associated values
Most of Swift Concurrency Needs a runtime and a scheduler Interrupt handlers and your own loop, or follow the current status

What remains is a lot: the whole of the core language, generics, value types, the standard library's essential types (Int, UInt8, Array, Optional, Result, Range, InlineArray, Span), unsafe pointers for registers, and @inlinable-style optimizations. Many things that sound lost, like protocols, are still there; it is only their dynamic form that is gone.

Designing without existentials

The first habit to learn is to replace any Protocol with a generic parameter. An existential value is a box that remembers its type at runtime; a generic parameter is fixed at compile time, so the compiler can inline everything. The next example defines a tiny hardware abstraction (an output pin), a real-looking Blinker that works with any pin type, and a wrapper pin for an LED wired the other way round. A simulated pin stands in for a chip; on a board you would conform a type that writes a register.

Swift A hardware abstraction with generics, not existentials

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both blinkers are different types: Blinker<SimulatedPin> and Blinker<ActiveLow<SimulatedPin>>. The compiler generates a separate, fully optimized tick for each, with the pin write inlined. Compare this with an array [any OutputPin], which would mean a dynamic call through a table. That form is exactly what Embedded Swift does not allow for ordinary protocols, and with generics you rarely miss it. The cost is code size if you instantiate very many different types, so keep an eye on that in real firmware.

Errors without any Error

Regular throws can throw anything, so Swift stores the error in an existential. Typed throws names the exact error type, so the error is a plain enum value with no box. This is the error style that suits firmware, and a good protocol parser is the classic example. The next program decodes a five-byte sensor packet: a header byte, a sensor id, a signed 16-bit temperature in thousandths of a degree, and a checksum. Notice &+ and &-, the wrapping operators:

Swift Parsing a sensor packet with typed throws and wrapping math

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The checksum trick is worth knowing: the sender stores the negated sum, so the receiver can add all the bytes including the checksum and expect zero. It only works because &+ and &- wrap around modulo 256. The packet for -5.25 degrees shows how a signed value is carried in two unsigned bytes: UInt16(bitPattern:) reinterprets the bits of an Int16, and Int16(bitPattern:) reverses it. These bit-pattern initializers never trap, because no value changes, only its interpretation.

Overflow is a trap, so choose your operator

In normal Swift, + on integers traps (stops the program) when the result does not fit. That is a safety feature, but on a device without a screen a trap means a silent reset or a hang, so you must decide deliberately what overflow should do:

Swift UInt8 addition overflows at run time (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The run prints start and then the program dies: the sum 300 does not fit in a UInt8, so the checked addition traps. The runner reports the signal that ended the process, SIGILL (illegal instruction), which is how an optimized Swift build shows a trap, without any message text. The fix depends on what you mean. If wrapping is the intended behavior (checksums, hashes, counters), use &+. If you want to know about the overflow, use addingReportingOverflow(_:), which returns the wrapped value and a flag. If you want the biggest value instead of a wrap, clamp it yourself. The numbers lesson covers all three. The key habit for firmware is to never leave the choice to chance.

Talking to hardware: registers

A microcontroller's peripherals (pins, timers, serial ports) are controlled through memory-mapped registers: special addresses where reading or writing a 32-bit word has an effect outside the chip. In Swift you reach them through an UnsafeMutablePointer. The next program builds a small, safe wrapper around such a pointer with named bit operations, and runs it against ordinary allocated memory standing in for a register:

Swift A register wrapper, tested on simulated memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

On real hardware the pointer would be created from a datasheet address, with code like the following. This is a read-only example, and the address is a placeholder, not a real chip's:

Swift
// Read-only example: do not run on a PC. The address is a made-up placeholder.
let gpioOutput = Register(UnsafeMutablePointer<UInt32>(bitPattern: 0x4000_0000)!)
gpioOutput.setBits(1 << 3)

There is one serious caveat. Swift has no volatile keyword. The optimizer is allowed to remove a write whose value is never read back by the program, or merge two writes, and that is wrong for a hardware register where every access matters. Real projects solve this with a tiny C header that declares the registers volatile and wraps each access in a function, or with a library such as swift-mmio, which generates safe register APIs from a description. The wrapper type above is the shape those libraries take: a small value type with named operations, so that application code never touches raw pointers.

Fixed-size storage: no heap

Arrays and strings allocate memory on the heap, and many small devices have no heap allocator or too little memory to risk one. Firmware uses fixed-capacity structures whose size is known at compile time. Swift's InlineArray stores its elements inline in the struct, with the count as part of the type, and recent Swift versions let your own types take an integer generic parameter too. Here is a ring buffer, the structure behind almost every serial port driver:

Swift A heap-free ring buffer with an integer generic parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The buffer's capacity is part of its type, so RingBuffer<4> and RingBuffer<64> are different types with different sizes, and neither ever calls the allocator. When the buffer is full, push reports failure instead of growing, which is the right policy in a real-time system: the caller decides whether to drop the byte, flag an overrun or stop the sender.

State machines with value types

Firmware is mostly reacting to events: a button changes, a timer fires, a byte arrives. Enums and structs make such logic easy to write and to test off the device. A classic problem is debouncing: a mechanical button flickers for a few milliseconds when pressed. This debouncer accepts a new state only after it has been seen several samples in a row:

Swift A button debouncer you can test on a computer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Nothing in Debouncer knows about hardware, so you can test it on a laptop with scripted input, as above, and run the identical code on the chip, where feed is called from a timer interrupt. That separation, a pure core with a thin hardware layer, is the single most useful architecture for embedded code, in any language.

Building and flashing

The remaining steps need a cross-compiling toolchain and a physical board, so this section is a read-only example. A Swift package for a microcontroller turns on the Embedded feature for its target and compiles for a bare-metal triple, such as the one for a Cortex-M chip:

Swift
// Read-only example: Package.swift (shape only; settings vary per chip and release)
// swift-tools-version: 6.2
import PackageDescription

let package = Package(
    name: "Blink",
    targets: [
        .executableTarget(
            name: "Blink",
            swiftSettings: [
                .enableExperimentalFeature("Embedded"),
                .unsafeFlags(["-wmo"]),
            ]
        )
    ]
)
Terminal
# Read-only example: compile one file for an ARM Cortex-M chip, then inspect its size
swiftc -target armv7em-none-none-eabi -enable-experimental-feature Embedded -wmo \
       -Xfrontend -function-sections -Osize -c main.swift -o main.o
size main.o

A real project also needs a linker script (describing where flash and RAM live), a start-up routine that sets up the stack and calls your code, and a flashing tool for the board. The official Swift Embedded examples repository provides ready-made versions of these for popular boards, and it is the recommended starting point. The entry point of the program is a main function, usually a top-level loop that never returns:

Swift
// Read-only example: the shape of firmware (hardware names are illustrative)
@main
struct Firmware {
    static func main() {
        var blinker = Blinker(pin: BoardLED())     // BoardLED writes a real register
        while true {
            blinker.tick()
            delay(milliseconds: 500)               // a busy wait or timer provided by your board code
        }
    }
}

When to use it, and when not to

Embedded Swift is a good fit when you want modern safety and expressiveness on a small device, when the team already knows Swift, when you want to share code with apps and servers, or when you are building a new product on a chip that is already supported. It is a poor fit if you need a long-term, vendor-certified toolchain for a safety-critical product today, if your chip's ecosystem (drivers, RTOS, certification kits) is built around C, or if your device is large enough that regular Swift on a small Linux board would do. In that last case, Swift on Linux with normal Foundation is much easier. Wherever it fits, the best way to start is the way this lesson did: write the logic as pure, testable Swift first, and attach it to the hardware last.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main idea of Embedded Swift?

    Embedded Swift is a compilation mode. The compiler resolves types at build time, specializes generics and drops the runtime machinery that needs metadata.
  2. 2. Which replacement does Embedded Swift expect for [any OutputPin]?

    Generics are resolved at compile time and fully specialized, so no runtime table is needed. Existentials of ordinary protocols are not available.
  3. 3. Why does firmware prefer throws(PacketError) over plain throws?

    Untyped throws stores the error as an existential. A typed error enum needs no box and no runtime support.
  4. 4. What does sum &+ byte do when the sum would not fit in a UInt8?

    The & operators use wrapping arithmetic and never trap. Use them when wrap-around is the intended behavior, as in checksums.
  5. 5. Why is the debouncer written as a plain struct with no hardware access?

    A pure core is easy to test with scripted input. A thin hardware layer calls it from an interrupt or a loop.

Summary

  • Embedded Swift compiles the same language without the dynamic runtime, producing tiny self-contained programs for microcontrollers and similar targets.
  • It trades away existentials of ordinary protocols, untyped throws, reflection, Codable, Foundation and most heavy library features.
  • Design with generics instead of any Protocol, typed throws for errors, wrapping operators or explicit overflow handling for arithmetic, and InlineArray or integer generic parameters for fixed-size storage.
  • Hardware registers are reached through unsafe pointers wrapped in small value types; because Swift has no volatile, real projects use a C shim or a library such as swift-mmio.
  • Keep the logic pure and testable on a computer, and keep the hardware layer thin.
  • Build flags, supported chips and feature status change quickly, so always check the current release notes and the official Embedded examples.

Next: Project: Expression Calculator