swift-path-matcher: The Swift Router That Turns URL Parsing Into a Type Problem

A tiny DSL, a result builder, and a careful solution to tuple flattening, type erasure, and clean route outputs.

8 min read • View on GitHub • More from sunghyun-k

A wide editorial scene of a mechanical switchboard turning messy URL segments into clean typed outputs. Path fragments enter as a tangled stream on one side, while only the meaningful parameters emerge on the other side in orderly slots.
The library’s core idea is simple to say and harder to build: keep the routing API declarative, then hide the type machinery that makes the output stay flat and readable.
Key Takeaways

A Router That Refuses to Leak Its Internals

Most routing code starts as a pile of string checks. This one starts as a declarative shape. You describe the path once, and the library turns it into a matcher that returns typed values instead of forcing you to peel apart path[0], path[1], and whatever comes next.

That is the real appeal of swift-path-matcher. The public API stays small and readable, but the package quietly uses Swift’s result-builder system and generic plumbing to keep the surface area clean.

A close-up of modular path blocks snapping together. Fixed literal blocks fade into the background while parameter blocks remain visible and connect into a flat output strip. The image explains why the matcher returns data without leaking structural path pieces.
Literals are structure. Parameters are data. The library draws a hard line between the two so route handlers only receive what they actually need.

The Trick: Literals Disappear, Parameters Survive

The library’s key opinionated move is simple. Fixed path segments are treated as Void. Parameters are treated as values. That means the matcher can build a route definition out of many pieces without polluting the final output with every literal marker along the way.

That design matters because route handlers should care about meaning, not scaffolding. If a path contains /users/:id/posts/:postID, the caller wants id and postID. It does not want a tuple full of dead weight just because the path needed a few constant separators.

The builder removes structure from the output and keeps only the values that matter. That is what makes the DSL feel small even when the type system underneath is not.

Why the Tuple Flattening Matters

This is the technical centerpiece. Without flattening, a builder chain would quickly devolve into nested tuples that are awkward to read, awkward to name, and awkward to pass around. The package solves that with builder extensions and factory logic that combine pieces into a flat shape instead of preserving every intermediate layer.

Design choiceResultWhy it matters
Nested tuplesHard to read and unpackLeaks implementation detail into the public API
Flat tuple outputReadable route valuesKeeps handlers focused on business logic
Void for literalsStructure disappearsOnly parameters remain in the match result
Generic builder compositionDeclarative route definitionsLets Swift do the wiring without making callers pay for it

The payoff is not just aesthetic. A flat result type makes route handlers more composable, easier to test, and less annoying to refactor. That is a small ergonomic gain with an outsized effect on daily use.

The Router Is Just a Registry, Which Is the Point

Once the matcher exists, the router can stay plain. It strips scheme and host, splits the URL into segments, then checks registered handlers in order until one returns a match. That is the right place for boring code. The cleverness belongs in the matcher, not the dispatch loop.

final class PathRouter {
    func handle(_ url: URL) {
        let segments = url.path.split(separator: "/").map(String.init)
        for handler in handlers {
            if let output = handler.matcher.match(segments) {
                handler.perform(output)
                return
            }
        }
    }
}

The internal type erasure is doing quiet work here. The router can store handlers together, but each handler still preserves the type safety of the closure it was built with. That is a good pattern for small libraries: erase where storage demands it, keep generics where the API benefits from them.

Literal Matching Is More Practical Than It First Looks

The package does not stop at exact string segments. It supports multi-segment literals and case-insensitive matching, which makes the DSL less fragile in real navigation scenarios. That is a subtle but important product decision. Routing libraries live or die on developer trust, and trust comes from predictable, forgiving matching behavior.

This is where the design stops feeling academic. The author is not trying to impress with raw pattern power. The focus is on making deep links, app navigation, and other URL-driven flows feel natural in Swift.

What This Beats, and What It Does Not

The cleanest comparison is against regex-heavy routing and broader path libraries. Regex gives you power, but it rarely gives you clarity. A bigger path utility like PathKit gives you more surface area, but that can be overkill if all you want is a focused matcher with typed route data.

ApproachStrengthTrade-off
Regex-based routingVery flexibleHarder to read, harder to maintain
Broad path librariesMore general-purposeRouting is only one concern among many
Manual string checksSimple at firstBrittle and repetitive
swift-path-matcherSwift-native DSL with typed outputsNarrow scope by design

That narrow scope is a feature. This repo is not trying to be a universal filesystem or path toolkit. It is trying to make one slice of routing elegant, and it succeeds by refusing to do too much.

Why This Feels Like a Swift-First DSL, Not a Wrapper

The best Swift frameworks do not just wrap existing ideas. They reshape them around the language. That is what happens here. Result builders make the syntax feel native, generic extensions hide the type machinery, and the final public API reads like a tiny language rather than a utility function.

That is the larger lesson. If you can isolate complexity inside a few carefully engineered layers, you can give callers a declarative interface that feels effortless. Swift-path-matcher is interesting because it shows how far that pattern can go without turning into a framework zoo.