On this page
The short answerWhy Swift examples stop workingDecide what each block is meant to beRun scripts and type-check filesPut important examples in Snippets/Embed compiled snippets in DocCAssert behavior with Swift TestingExtract standalone Markdown fences for a basic checkLabel fences and read coverage honestlyRun package checks in CITriage failures before filing a docs bugWhere DocsAlive fitsPasteable checklistThe sources we checkedFAQThe short answer
Test Swift documentation examples in the toolchain, language mode and platform environment the page promises. Run standalone scripts, type-check suitable complete files, and put important package examples in SwiftPM’s Snippets/ directory so swift build compiles them. Use tests for promised values, mark fragments clearly, and record platform and dependency requirements. A compiler success is useful evidence, but it does not by itself prove that a reader can install the package or obtain the stated result.
Run the checks on documentation and API changes, before releases, and periodically for dependency drift. Swift 6.4.2 was released on October 29, 2026; the examples here use Swift 6.4.2 on Linux unless a platform is identified. State the toolchain and platform used for your own docs. See how to test documentation code for the wider workflow.
DocsAlive recognizes swift fences but skips them as not executable today. It can check supported blocks elsewhere on the page and classify findings, while your Swift build and tests supply the Swift-specific evidence.
Why Swift examples stop working
A Swift example can drift when an API changes its argument labels. A call that once used one label may no longer match the function a reader installs, even if the function name still looks familiar. APIs can also be removed, moved to another module or made unavailable on a target platform. A missing import can leave a reader with an error even though the author’s project already imports the required module.
Swift language mode matters as well. Swift 6 language-mode and concurrency checks can expose code that compiled under a different configuration. A check against a toolchain alone should therefore record the language mode and relevant build settings, rather than assuming every project using that toolchain receives identical diagnostics.
Platform assumptions are especially important for Swift packages. A README may show a UI example using UIKit, while a Linux CI runner has no UIKit. That failure can be a runner mismatch rather than an API defect. State that an example requires an Apple platform, test it on a suitable macOS runner, and keep platform-neutral package checks on Linux where appropriate.
Package setup can drift independently of the source. A wrong package URL, version requirement or product name can stop a reader before the example compiles. A local checkout build does not prove that the URL and version in a page lead to the same artifact. Test the install path in a clean consumer project as well as compiling the package’s own source.
DocC catalogs and SwiftPM package documentation often mix complete snippets with fragments and fenced listings. A short fragment may be useful inside a larger explanation, but a reader needs to know where it belongs. A listing presented as a complete script should include its imports and declarations, while a package snippet should declare the module it imports and rely only on the documented package context.
Decide what each block is meant to be
Choose the test after identifying the reader’s intended starting point. A swift fence can hold several different kinds of content.
| Block | Reader’s context | Appropriate check |
|---|---|---|
| Script | A file run directly with the Swift interpreter | Run swift file.swift and check its result |
| Package snippet | A file using a package target or a direct dependency | Compile it through swift build; run it when behavior matters |
| Fragment | Part of a larger scope or sequence | Mark it and test the surrounding program |
Package.swift |
A package manifest describing targets and dependencies | Build a representative package with that manifest |
| DocC fenced listing | Source displayed in documentation markup | Add a separate check; the listing itself is not compiled |
| Output listing | A result shown to a reader | Compare it with a controlled run if the page promises it |
A package snippet and a script may both contain top-level statements, but they do not have the same dependency context. A script that uses only the standard library may run directly. A snippet importing a package target needs a build that supplies that module. Similarly, a Package.swift file should be assessed as a manifest in a package, not merely as an arbitrary source file.
The fictional Acme SDK, module AcmeSDK and variable ACME_API_KEY are placeholders in this guide. They are not instructions to install or call a real service. In an actual SDK guide, use the real package URL, version and product names, and state any credential prerequisite without putting a real secret in the documentation.
Run scripts and type-check files
Save this complete standard-library script as hello.swift:
let name = "Ada"
print("Hello, \(name)!")
Run it:
swift hello.swift
It prints Hello, Ada!. This verifies that the script executes under the selected Swift environment. For a page that promises a specific output, compare the result in a separate test or review; a zero exit status alone does not establish that the displayed result is accurate.
For a fast check that does not execute the file, use:
swiftc -typecheck hello.swift
A type check can catch a missing name, an incorrect argument label or an incompatible type in a complete file. It does not exercise runtime behavior, verify output or prove that an external service is reachable. It also needs the appropriate module search paths and dependencies for code that imports a package.
For example, the following file is intentionally broken because a string is assigned to an integer:
let count: Int = "three"
Saving it as broken.swift and running swiftc -typecheck broken.swift fails with a diagnostic containing cannot convert value of type 'String' to specified type 'Int'. Keep deliberately broken examples clearly labeled in documentation and exclude them from a harness intended for working examples.
Check the environment as part of the promise
Record the Swift version, operating system, language mode and package versions alongside a result. For a package guide, also record whether the test used a checkout or the artifact a reader obtains from the published package URL.
Use a clean consumer project to follow the documented dependency instructions. If the test adds a dependency, import or build setting that the page does not mention, make that addition visible in the test record. A passing sample can otherwise conceal an instruction that a new reader still needs.
For code requiring UIKit or another Apple-platform-only framework, use a macOS runner with the required SDK and say so on the page. A Linux type check cannot establish whether that example works on its intended platform. Conversely, a macOS-only test does not establish Linux support for the rest of the package.
Put important examples in Snippets/
SwiftPM builds top-level files in a package’s Snippets/ directory as individual snippets. Each snippet is its own unit: it cannot rely on declarations from another snippet file. It can import the package’s targets and products of direct dependencies. This makes a snippet a useful home for a complete example that should remain tied to the package build.
Create a directory with this layout:
Greeter/
Package.swift
Sources/
Greeter/
Greeter.swift
Snippets/
greet-someone.swift
Save this manifest as Greeter/Package.swift:
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "Greeter",
products: [
.library(name: "Greeter", targets: ["Greeter"])
],
targets: [
.target(name: "Greeter")
]
)
Save the public function as Greeter/Sources/Greeter/Greeter.swift:
public func greeting(for name: String) -> String {
"Hello, \(name)!"
}
Save the complete snippet as Greeter/Snippets/greet-someone.swift:
import Greeter
print(greeting(for: "Ada"))
From the Greeter directory, build and run it:
swift build
swift run greet-someone
The run prints Hello, Ada!. The build compiles the snippet; the run also exercises its behavior. If the package has several files in Snippets/, a broken one can fail the build even if a different snippet is the one a reviewer intended to inspect.
Now consider this intentionally broken replacement for the snippet:
import Greeter
print(greeting(name: "Ada"))
The function’s argument label is for, not name. With this replacement in Snippets/greet-someone.swift, swift build fails with:
incorrect argument label in call (have 'name:', expected 'for:')
Restore the working snippet after the demonstration. This is precisely the kind of API drift a compiled sample can expose: the documentation file and the public declaration must agree at build time.
Embed compiled snippets in DocC
DocC can embed a snippet from the package rather than duplicating its source in a documentation page. For the preceding file, a DocC markup page can use:
@Snippet(path: "greet-someone")
The path form shown here follows current DocC guidance; before Swift-DocC 6.2.1, the path included the package and Snippets/ components. Check the version used by your documentation build when maintaining older packages.
A snippet can contain setup that the compiler needs but the rendered explanation should not emphasize. Use // snippet.hide and // snippet.show to control which lines DocC displays. Slices can select a named portion with // snippet.<id> and // snippet.end, then embed it with an @Snippet directive using path and slice. The whole source file still needs to compile, so hidden setup is part of the test even when a reader does not see it.
That creates a review responsibility: do not hide an import or setup step that the reader needs to reproduce the example unless the surrounding page supplies it. Hidden code can make a rendered listing look self-contained when it is not. Explain the prerequisites and inspect the rendered page as well as the build.
Fenced code listings written directly in DocC markup are not compiled by DocC. Prefer compiled snippets for examples that must keep working, and use direct listings for intentional fragments or illustrative material with an appropriate separate check. The DocC snippet guide documents embedding, visibility and slices.
The Swift-DocC plugin provides a SwiftPM workflow for documentation generation. Its dependency is available from version 1.1.0; follow its setup instructions for the package and toolchain in use. With the plugin configured, its documented preview command has this form:
swift package --disable-sandbox preview-documentation --target YourTarget
Replace YourTarget with the actual target. Previewing is useful for checking presentation and links, while swift build and tests provide separate evidence about compiled snippets and behavior.
Assert behavior with Swift Testing
Compilation catches the broken argument label, but it does not prove that greeting(for:) returns the value shown in the page. Add a test target to the Greeter manifest when using the following test:
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "Greeter",
products: [
.library(name: "Greeter", targets: ["Greeter"])
],
targets: [
.target(name: "Greeter"),
.testTarget(name: "GreeterTests", dependencies: ["Greeter"])
]
)
Save this as Greeter/Tests/GreeterTests/GreeterTests.swift:
import Testing
import Greeter
@Test func greetingForAda() {
#expect(greeting(for: "Ada") == "Hello, Ada!")
}
From the package directory, run:
swift test
This test checks the stable return value that the documentation promises. It is separate from the snippet’s build and run: the snippet demonstrates the reader-facing call, while the test makes the expected value an assertion. Keep them aligned when the API or wording changes. The Swift Testing project and Testing reference describe @Test and expectations.
For output containing timestamps, generated identifiers or ordering that is not guaranteed, assert the stable property that matters instead of copying a volatile transcript. If exact output is part of the contract, use a controlled environment and check the exact output there.
Extract standalone Markdown fences for a basic check
The following Python 3 script finds simple swift fences in Markdown, writes each selected block to a temporary .swift file and runs swiftc -typecheck. It skips a block when its first line is // fragment.
Save it as check_swift_fences.py:
import re
import subprocess
import sys
import tempfile
from pathlib import Path
FENCE = re.compile(
r"^```swift[ \t]*\r?\n(.*?)^```[ \t]*$",
re.MULTILINE | re.DOTALL,
)
def main() -> int:
if len(sys.argv) < 2:
print("Usage: python3 check_swift_fences.py FILE.md [FILE.md ...]")
return 2
passed = failed = skipped = 0
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
number = 0
for name in sys.argv[1:]:
path = Path(name)
try:
markdown = path.read_text(encoding="utf-8")
except (OSError, UnicodeError) as error:
print(f"Cannot read {path}: {error}")
failed += 1
continue
for match in FENCE.finditer(markdown):
number += 1
code = match.group(1)
line = markdown.count("\n", 0, match.start()) + 1
location = f"{path}:{line}"
if code.splitlines() and code.splitlines()[0].strip() == "// fragment":
print(f"SKIP {location}: fragment")
skipped += 1
continue
source = root / f"block_{number}.swift"
source.write_text(code, encoding="utf-8")
try:
result = subprocess.run(
["swiftc", "-typecheck", str(source)],
text=True,
capture_output=True,
check=False,
)
except OSError as error:
print(f"FAIL {location}: cannot start swiftc: {error}")
failed += 1
continue
if result.returncode == 0:
print(f"PASS {location}")
passed += 1
else:
print(f"FAIL {location}")
print(result.stderr.strip())
failed += 1
print(f"Summary: {passed} passed, {failed} failed, {skipped} skipped")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())
Run it with the compiler on PATH:
python3 check_swift_fences.py README.md
This script is intentionally narrow. It handles simple triple-backtick fences at the beginning of a line, not every Markdown construction, nested fence or tabbed format. It treats blocks independently, does not build a package or install dependencies, and does not run code or compare output. A package import may need module paths that this script does not provide; an Apple-platform-only import cannot be checked on Linux.
A // fragment marker prevents an isolated check from misrepresenting a partial listing as a complete file. It does not verify the fragment. Put consequential fragments in a compiled test or snippet with their surrounding context, and check that the page gives a reader enough information to use them.
Label fences and read coverage honestly
Use swift for Swift fences. In DocsAlive today, swift is recognized and skipped with the reason not executable (swift) and category not-executable. Supported blocks elsewhere on the page can still be checked.
The label swift-repl is unmapped. In the current engine, it can appear as a pass even though nothing was parsed or run. Treat that result as unchecked. A green status alone is not evidence that a Swift compiler accepted the listing; inspect the label, status and reason, and use your Swift checks for coverage.
Run package checks in CI
The following GitHub Actions outline uses the Swift 6.4.2 Bookworm container, checks out the repository and runs the package build and tests. It assumes Package.swift is at the repository root and the package is compatible with Linux.
name: Swift documentation
on:
pull_request:
push:
jobs:
swift-docs:
runs-on: ubuntu-latest
container:
image: swift:6.4.2-bookworm
steps:
- uses: actions/checkout@v7
- name: Build package and snippets
run: swift build
- name: Run tests
run: swift test
The build checks package snippets in Snippets/; the test command checks the project’s tests. Neither automatically checks arbitrary Swift fences in a README or DocC page. Add the fence script for the standalone listings it supports, and add consumer-project checks for the documented package URL and version.
Use a macOS runner and the appropriate Apple SDK for examples that import UIKit or other Apple-platform-only frameworks. State that requirement on the page and in the test record. Keep Linux and macOS results distinct so a platform mismatch does not hide either a real portability issue or a valid platform-specific example.
Run the relevant suite when a pull request changes the API or docs, against a release candidate before shipping, and on a schedule when external dependencies can change. After publication, a clean consumer check against the published package answers whether the reader’s install path works. A post-release check supplies evidence after the fact; it cannot serve as a gate for a release that has already shipped.
Triage failures before filing a docs bug
Keep the page, line, command, toolchain, platform and dependency versions with each finding. A diagnostic identifies the immediate failure; the surrounding documentation determines whether it is a defect in the page, a missing prerequisite or a mismatch in the test environment.
| Finding | What to investigate | Likely action |
|---|---|---|
| Incorrect argument label | Whether the example targets the installed API version | Update the call or the documented version |
| Missing module | Whether the page states the import and package dependency | Add the missing instruction or correct the test setup |
| UIKit missing on Linux | Whether the example is intended for an Apple platform | Test on macOS and state the platform requirement |
| Swift 6 concurrency diagnostic | The language mode and settings promised by the page | Reproduce under the supported configuration and update the code or guidance |
| Fragment fails independently | Whether the page supplies its enclosing context | Test the complete context and label the fragment |
| Package URL or version fails | Whether the published dependency instructions are correct | Verify the real URL and release in a clean consumer project |
| Output differs after a successful run | Whether the result is a stable promise or representative output | Reproduce and update the test or the page |
| Credential or fixture missing | Whether a prerequisite is documented and safe to supply in a separate test | Record the gap and review the instructions |
| Timeout or network error | Whether the service or network was available | Retry or investigate before assigning a documentation cause |
A fictional placeholder failure is not evidence that an actual SDK is unavailable. Likewise, a test that silently provides a missing import can make a page look healthier than it is for a reader. Preserve those distinctions in the report and in the fix.
Where DocsAlive fits
DocsAlive extracts fenced blocks with their page and line, plans supported checks and reports results with categories and reasons. It keeps supported examples in page order and uses a fresh container for each page. Its triage helps distinguish likely documentation bugs from missing context, credentials, fixtures and runner limitations. See framework support and findings.
Swift execution is not available in the product today, so pair its report with swift build, swift test and any standalone checks your pages need. A recognized swift block is a skip, not a successful type check. A scan without --execute only extracts and plans; enabling execution does not make Swift blocks executable.
Printed output is compared only for Python pycon or python-repl sessions. A separate output block is recognized and skipped, and its contents are not compared. Use Swift tests or another explicit check for the values and output your Swift documentation promises.
Pasteable checklist
Copy this into a pull request or release checklist:
- [ ] State the tested Swift version, language mode and platform.
- [ ] Identify scripts, package snippets, fragments and manifests.
- [ ] Label Swift fences
swiftand mark intentional fragments. - [ ] Run complete scripts that promise executable behavior.
- [ ] Type-check suitable standalone files with their required imports.
- [ ] Put important package examples in
Snippets/and runswift build. - [ ] Check each snippet independently; do not rely on another snippet’s declarations.
- [ ] Use tests to assert stable values promised by the page.
- [ ] Review hidden snippet lines against the rendered prerequisites.
- [ ] Verify package URLs, versions and products in a clean consumer project.
- [ ] Test Apple-platform-only examples on macOS with the required SDK.
- [ ] Record skipped blocks, credentials, fixtures and platform limitations.
- [ ] Check the release candidate and, when practical, the published package.
- [ ] Review diagnostics in context before labeling them documentation bugs.
The sources we checked
These sources were read on November 11, 2026.
| Source | What it covers |
|---|---|
| Swift installation | Toolchains and the Swift 6.4.2 release |
| Swift-DocC documentation | Documentation catalogs and DocC |
| Adding code snippets to content | Snippet files, embedding, hidden lines and slices |
| Swift-DocC plugin | SwiftPM documentation workflow and preview |
| Swift Testing and Testing reference | Tests and expectations |
| Official Swift container images | Swift container tags for CI |
| actions/checkout | Repository checkout in CI |
| Findings | Product reporting and triage context |
FAQ
Does swiftc -typecheck run a Swift example?
No. It checks the file without executing it. Run scripts or package snippets separately, and use tests when the documentation promises a particular value or behavior.
Does DocC compile fenced code listings?
No. A fence written directly in DocC markup is displayed as a listing but is not compiled. Put examples that must keep working in package snippets or provide another explicit check.
What does swift build check in Snippets?
It compiles each file in the package's top-level Snippets directory as its own snippet unit. A snippet cannot use declarations from another snippet file, so include its required context and imports.
Why did a UIKit example fail on Linux?
UIKit is an Apple-platform framework and is not available in a Linux Swift environment. Test that example on a suitable macOS runner and state the platform requirement on the page.
Does a Swift pass in DocsAlive mean the code was checked?
No. A swift fence is recognized and skipped as not executable. The unmapped swift-repl label can appear as a pass without being checked, so use swift and rely on separate Swift tooling.
How can a team catch changed argument labels?
Compile examples against the intended package version, preferably through package snippets for reader-facing calls. A clean consumer build also checks whether the documented dependency setup reaches that version.




