← All languages

Servirtium for

Swift

Ships a built package on the GitHub release. Release v2.0.0-alpha.20.

FFI mechanism
clang module map over the C ABI. Swift calls libservirtium_vcr's flat C ABI directly through a clang module map (CServirtiumVcr); no glue .c file. In the shipped form SwiftPM downloads the core as a checksum-verified static-library artifact bundle (binaryTarget), so it is linked into your binary and nothing is found at run time.
Toolchain
Swift 6.2+ to build against the artifact bundle (static-library bundles, SE-0482); swift-tools-version 5.9 in your manifest; macOS 13+ (arm64 or x86_64) or Linux glibc (x86_64 or arm64). Windows, FreeBSD and Linux musl use the source form.
Distribution
Ships: servirtium-vcr-swift-v2.0.0-alpha.20.artifactbundle.zip, pulled by SwiftPM from: "2.0.0-alpha.20"
Finding the library
Artifact form: none needed, the static core is linked into your binary. Source form (other platforms, or main between releases): SERVIRTIUM_VCR_LIB_DIR must hold a file named exactly libservirtium_vcr.so / .dylib; it is baked in as an rpath, and setting it selects the source form.
On GitHub
swift/ · README

Getting it

This language has a built artifact on the release: no source to vendor.

  1. Add the package to your Package.swift by version. SwiftPM downloads and verifies the artifact bundle for you; there is nothing else to fetch or set. Do NOT set SERVIRTIUM_VCR_LIB_DIR with this form (it switches to the source form, which SwiftPM refuses for a from: dependency).
    // swift-tools-version:5.9
    import PackageDescription
    let package = Package(
        name: "yourapp",
        platforms: [.macOS(.v13)],
        dependencies: [
            .package(url: "https://github.com/servirtium/servirtium-vcr", from: "2.0.0-alpha.20"),
        ],
        targets: [
            .executableTarget(name: "yourapp", dependencies: [
                .product(name: "Servirtium", package: "servirtium-vcr"),
            ]),
        ]
    )
    
  2. Check it: resolve, download the bundle, link, and report a missing tape (prints 'servirtium linked and loaded: ...').
    mkdir -p Sources/yourapp && cat > Sources/yourapp/main.swift <<'EOF'
    import Servirtium
    do { try Vcr.withPlayback("/nonexistent.md") { _ in } } catch { print("servirtium linked and loaded: \(error)") }
    EOF
    swift run yourapp
    
  3. Source form, for Windows, FreeBSD, Linux musl, or main between releases: depend on a branch and link a downloaded shared library yourself. The directory must hold the library under the plain name.
    # Package.swift: .package(url: "https://github.com/servirtium/servirtium-vcr", branch: "main")
    export SERVIRTIUM_VCR_LIB_DIR="$HOME/.servirtium-vcr/v2.0.0-alpha.20"; mkdir -p "$SERVIRTIUM_VCR_LIB_DIR"
    curl -fsSL -o "$SERVIRTIUM_VCR_LIB_DIR/libservirtium_vcr.so" \
      "https://github.com/servirtium/servirtium-vcr/releases/download/v2.0.0-alpha.20/libservirtium_vcr-v2.0.0-alpha.20-linux-x86_64-musl.so"
    swift build      # keep SERVIRTIUM_VCR_LIB_DIR exported for build, run and test
    

Record

Point your client at the VCR's base URL; the VCR forwards to the real service and hands back the real response. Nothing is written until you commit.

import Servirtium

try Vcr.withRecord("tapes/climate_api.md", upstreamBase: "https://example.org") { rec in
    let body = try httpGet(rec.baseUrl + "/countries")   // your HTTP helper
    try rec.flush()    // commit: writes the tape
}
// a body that throws DISCARDS the recording; one that ends with neither
// flush() nor discard() makes withRecord throw and writes nothing

Playback

The same tape, replayed with no network.

import Servirtium
import XCTest

try Vcr.withPlayback("tapes/single_get.md") { vcr in
    let body = try httpGet(vcr.baseUrl + "/ok")
    XCTAssertEqual(body, "ok-body")
    XCTAssertEqual(vcr.lastKind, .ok)
}   // <- the scoped form closes the server on every path, throws included

Idiomatic extras

A failed test discards the recording

withRecord discards if the body throws, so a failed test cannot overwrite a good tape; rec.discard() drops it explicitly.

try Vcr.withRecord("tapes/api.md", upstreamBase: upstream) { rec in
    try runTest(rec.baseUrl)     // throws -> recording discarded
    try rec.flush()
}

Redact secrets before the tape is written

Config calls throw VcrError carrying the core's reason. Register the same rules on the playback handle.

try rec.redactCredentials()                         // Authorization, Cookie, X-Api-Key, ...
try rec.redactCredentialHeader("X-Tenant-Token")
try rec.redactHeader("X-Request-Signature")

Volatile values and a rewritten upstream base

Name a value that changes every run with a {{placeholder}}; a response token no request binds must be bound before start.

try rec.volatileRule("request body", "<a:MessageID>urn:uuid:{{messageId}}</a:MessageID>")
rec.rewriteUpstreamBase()
// playback side, binding before start:
let v = try Vcr.playbackUnstarted(tape); try v.bind("caseId", "42"); try v.start()

Gotchas

  • The artifact bundle needs Swift 6.2 or newer; an older toolchain fails to read it (use the source form).
  • Covered by the bundle: macOS arm64 and x86_64 (13+) and Linux glibc x86_64 and arm64. Windows, FreeBSD and Linux musl: source form.
  • Use from: or exact: with a release that has the bundle. SERVIRTIUM_VCR_LIB_DIR selects the source form, which SwiftPM rejects for a version dependency with 'contains unsafe build flags'.
  • A version resolves to the bare semver tag (2.0.0-alpha.20); if Package.resolved shows the v-prefixed commit, the release workflow had not finished: swift package update.
  • On Linux write your HTTP helper against FoundationNetworking (import it under #if canImport(FoundationNetworking)); the bare Foundation import fails with a confusing URLSession error.
  • A checksum mismatch error means the bundle on the release page is not the one the manifest names; report it, do not work around it.

Prompt for your coding agent

Paste this into Claude, Codex, Gemini or any coding agent, in your Swift project. It wraps one of your existing integration tests with Servirtium. The general prompt has a slot for the language instead.

Hey Gemini or Claude or Codex,

I want a test in this Swift project to run without calling a real web service every time. Use Servirtium (https://servirtium.dev), which records HTTP conversations as readable Markdown "tapes" and replays them. Do these steps in order and tell me what you did at each one.

1. Find an existing integration test in this project that calls a web service as a side effect of what it is testing. Prefer one that is slow, flaky, or needs credentials or network because of that call. Tell me which test you chose and why.

2. Add the Servirtium binding for Swift. Follow https://servirtium.dev/languages/swift/ exactly. Servirtium ships a built package for this language on the GitHub release v2.0.0-alpha.20: servirtium-vcr-swift-v2.0.0-alpha.20.artifactbundle.zip, pulled by SwiftPM from: "2.0.0-alpha.20".
   Toolchain and minimum version: Swift 6.2+ to build against the artifact bundle (static-library bundles, SE-0482); swift-tools-version 5.9 in your manifest; macOS 13+ (arm64 or x86_64) or Linux glibc (x86_64 or arm64). Windows, FreeBSD and Linux musl use the source form..
   How the binding finds the native library: Artifact form: none needed, the static core is linked into your binary. Source form (other platforms, or main between releases): SERVIRTIUM_VCR_LIB_DIR must hold a file named exactly libservirtium_vcr.so / .dylib; it is baked in as an rpath, and setting it selects the source form.

3. Route that test's HTTP client to the Servirtium VCR's base URL instead of the real service, using the idiomatic Swift way of setting a base URL or HTTP client. The VCR starts on its own port (use port 0, so it picks a free one) and gives you its base URL; give that URL to the client and never hard-code a port.

4. Run the test once in record mode against the real service. Commit the recording when the test passes and discard it when the test fails: a record VCR that is closed without a commit or a discard writes no tape and raises an error. Use redact_credentials (the spelling for Swift is on the page) so secrets become numbered tokens, and remove volatile request headers such as User-Agent and Date from the tape so playback does not depend on them.

5. Keep the tape beside the test as readable Markdown, in version control. Open it and check there are no secrets or personal data in it before committing.

6. Make the test play back by default, with an explicit switch (for example an environment variable such as SERVIRTIUM_RECORD=1) that re-records.

7. Prove it works offline: make the real service unreachable (network off, or a wrong host) and show the test still passes in playback.

Traps to avoid:
- A record VCR needs Commit() or Discard(); closing it without either writes nothing and raises.
- The VCR runs in your test process on its own port; the system under test must use the VCR's base URL, not the real one.
- The artifact bundle needs Swift 6.2 or newer; an older toolchain fails to read it (use the source form).
- Covered by the bundle: macOS arm64 and x86_64 (13+) and Linux glibc x86_64 and arm64. Windows, FreeBSD and Linux musl: source form.
- Use from: or exact: with a release that has the bundle. SERVIRTIUM_VCR_LIB_DIR selects the source form, which SwiftPM rejects for a version dependency with 'contains unsafe build flags'.
- A version resolves to the bare semver tag (2.0.0-alpha.20); if Package.resolved shows the v-prefixed commit, the release workflow had not finished: swift package update.
- On Linux write your HTTP helper against FoundationNetworking (import it under #if canImport(FoundationNetworking)); the bare Foundation import fails with a confusing URLSession error.
- A checksum mismatch error means the bundle on the release page is not the one the manifest names; report it, do not work around it.

References:
- This language's page: https://servirtium.dev/languages/swift/
- The binding's directory: https://github.com/servirtium/servirtium-vcr/tree/main/swift
- Concepts, features and every language's quick start: https://servirtium.dev/llms-full.txt (index: https://servirtium.dev/llms.txt)

How these snippets were checked

Linux x86_64 (cachyos, Swift 6.4.2): a fresh package depending on .package(url:, from: "2.0.0-alpha.20") resolved, downloaded and verified servirtium-vcr-swift-v2.0.0-alpha.20.artifactbundle.zip, built, and ran a record-then-replay program (Vcr.withPlayback of single_get.md as the stand-in upstream, Vcr.withRecord with redactCredentials + note + flush(), then withPlayback of the new tape: live ok-body, replay ok-body .ok matchedCleanly true); a withRecord body ending without flush threw 'without commit or discard' and wrote nothing; a throwing body discarded; the extras (redactHeader, redactCredentialHeader, volatileRule, rewriteUpstreamBase, discard) ran. macOS binary form not run (Mac not used for SwiftPM network fetch); the source form was not run.

They mirror these files in the repository:

See also the feature reference, llms.txt and the swift/ directory.