swift-yaml

YAML 1.2.2 · RFC 9512 · Swift 6.2+

YAML for Swift, with no C underneath.

A complete YAML parser, emitter and Codable bridge written in pure Swift. It is memory-safe by construction, every type is Sendable, and hostile input fails with an error instead of a crash, on any thread.

service.yamlYAML
name: web
replicas: 3
ports: [80, 443]
debug: no   # a string in YAML 1.2
Service.swiftSwift
import YAML

struct Service: Codable, Sendable {
    var name: String
    var replicas: Int
    var ports: [Int]
}

let service = try YAMLDecoder()
    .decode(Service.self, from: text)
402 / 402yaml-test-suite cases, events and errors
0dependencies: no Foundation, no libyaml
512 levelsof nesting, safe on a 512 KiB thread
3.2×faster than Yams at loading a large file

safety

Untrusted YAML can't take your process down.

Configuration files come from users, pull requests and the network. swift-yaml treats every one of them as hostile: no C to overflow, no unbounded recursion, and every failure is a typed error with a line and column.

  • Pure Swift, strict memory safety

    Built with Swift's strict memory safety checking and without a single C dependency. Yams wraps libyaml; swift-yaml has no C code to audit.

  • Bounded nesting and alias expansion

    YAMLLimits caps nesting at 512 levels and alias expansion at a million nodes, so a "billion laughs" document fails with .limitExceeded.

  • No recursion per level

    Composing, constructing, comparing, hashing and emitting walk nested collections with explicit stacks. Depth never depends on the size of the thread's stack.

  • Validated input

    UTF-8, UTF-16 and UTF-32 with or without a byte order mark. Overlong sequences, lone surrogates and control characters are rejected, as in libyaml's reader tests.

YAMLErrortyped throws
2:1: error: scanner: found a line of a flow collection with insufficient indentation:
b: 3
^

concurrency

Built for Swift 6 strict concurrency.

Every public type is a Sendable value and parsing touches no shared state. Parse in task groups, actors or background queues without locks or @unchecked workarounds.

  • Sendable everywhere

    YAMLValue, YAMLNode, YAMLDocument, options, errors, encoder and decoder: all value types that cross isolation boundaries freely.

  • Safe on small stacks

    Swift concurrency and Dispatch threads have 512 KiB of stack. swift-yaml's tests parse, compare and emit 512-level documents on a thread of exactly that size.

  • A ~Copyable streaming parser

    YAMLParser can't be copied by accident, so its state always has one owner while it hands out events.

  • No global state

    No shared caches, no singletons and no C library state, so two documents never interfere.

Parse many files in parallelSwift
let values = try await withThrowingTaskGroup(of: YAMLValue.self) { group in
    for text in texts { group.addTask { try YAMLValue(parsing: text) } }
    return try await group.reduce(into: []) { $0.append($1) }
}

performance

Two to three times faster than Yams at reading YAML.

Pure Swift with no C bridge to cross: the scanner works directly on UTF-8 bytes and builds each string once. Reading a large file takes 2 to 4 times fewer allocations than Yams. Emitting is the exception, where Yams' libyaml writer is still faster.

Task, large catalogueswift-yamlYamsSpeed-up
Parse to a value
YAMLValue(parsing:) / Yams.load
70.1 ms227.4 ms3.2× faster
Compose a node graph
YAMLDocument.parse / Yams.compose
52.7 ms140.5 ms2.7× faster
Decode with Codable
YAMLDecoder / Yams' YAMLDecoder
92.2 ms162.4 ms1.8× faster
Encode with Codable
YAMLEncoder / Yams' YAMLEncoder
198.2 ms583.0 ms2.9× faster
Emit YAML text
value via YAMLEmitter / node via Yams.serialize
97.5 ms35.9 ms2.7× slower

Median (p50) wall-clock time of a release build on an Apple silicon Mac with macOS, measured with package-benchmark on a generated catalogue file. The bar shows each swift-yaml time as a share of the slower of the two. Run swift package --package-path Benchmarks benchmark to reproduce.

api

A modern Swift API at every level.

Pick the level you need: a streaming event parser, a node graph with tags, anchors and source locations, an order-preserving value, or Codable.

  • Typed throws

    Every parsing call throws YAMLError, so catch blocks know the error type without casting.

  • Borrowed input

    Parse an array, a slice, Data or a borrowed Span<UInt8> without copying it first.

  • YAMLValue

    Order-preserving, Hashable, Codable and expressible by literals. Its description is YAML.

  • An emitter that round-trips

    Picks a style for every scalar so it reads back identically, and keeps the styles, tags and anchors of a YAMLNode.

Values and literalsSwift
let config = try YAMLValue(parsing: "name: web\nports: [80, 443]")

config["name"]?.stringValue      // "web"
config["ports"]?[1]?.intValue    // 443
config == ["name": "web", "ports": [80, 443]]   // true

conformance

The whole spec, checked against the official tests.

Block and flow collections, all five scalar styles, anchors and aliases, tags and %TAG handles, directives, multi-document streams and complex keys.

  • yaml-test-suite

    All 402 cases (events and errors), all 279 JSON comparisons, and a round trip of all 308 valid inputs through its own emitter.

  • RFC 9512

    The YAML media type: encoding detection, fragment identifiers (#*anchor, #/json/pointer) and protection against alias bombs.

  • Every schema

    Failsafe, JSON and core (the YAML 1.2 default), plus YAML 1.1 with merge keys, picked by a %YAML 1.1 directive or on request.

  • Yams' and libyaml's tests

    Yams' test suite and libyaml's reader, nesting and emitter tests, ported to Swift Testing.

Add it to your package.

Swift 6.2 or later. Linux needs nothing beyond the standard library and libm; Apple platforms need OS 26.

Coming from Yams? The migration guide maps its API to this one.

dependencies: [
    .package(url: "https://github.com/mackoj/swift-yaml.git", from: "0.1.0"),
],
targets: [
    .target(name: "MyTool", dependencies: [
        .product(name: "YAML", package: "swift-yaml"),
    ]),
]