Skip to content
Tutorials Center
My learning

Topics

Lesson 114 of 146 ยท Advanced Swift

Documentation Comments

Write Swift documentation comments that tools understand: /// and /** */ syntax, Parameters, Returns, Throws, callouts, symbol links, DocC, and #warning markers.

Code tells the computer what to do. Documentation comments tell the next human what the code is for, what it promises, and what can go wrong. In Swift they are not just comments: a special form is parsed as Markdown, attached to the declaration that follows it, shown in Xcode's Quick Help and in autocomplete in many editors, and turned into websites by DocC, Swift's documentation compiler. The standard library is documented this way, which is why hovering over Array.firstIndex(where:) shows a neat description with parameters and a complexity note.

This lesson teaches the syntax, the standard sections, the callouts and links, and the habits that separate useful documentation from noise. Everything that needs Xcode, DocC or SwiftPM is clearly marked read-only, but we also build a tiny doc-comment reader in Swift that runs here, so you see exactly what a tool does with the markup.

Compilers ignore comments, including documentation comments, so a documentation mistake never fails the build. Tools like DocC check the links and report broken ones, but nothing checks that your text is true. Keeping docs and code in step is a review habit, not a compiler feature.

Three kinds of comments

Swift has three comment forms that are easy to confuse:

  • // text is a normal line comment. Use it for notes to the reader of the implementation.
  • /* text */ is a block comment. Swift allows them to nest, which makes it safe to comment out code that already contains comments.
  • /// text and /** text */ are documentation comments. They describe the declaration that follows directly and are meant for people who use it.

Put the documentation comment immediately before the declaration, with no blank line in between:

Swift Documentation comments on real declarations

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 program prints 12 14, then Rectangle(width: 6, height: 8) and 1200. The comments changed nothing at run time; their value shows up in your editor when you hover over area or scaled(by:), and in generated documentation. The double backticks (``area``) are symbol links, which DocC resolves to the property or method of that name.

Anatomy of a good comment

Documentation is Markdown with a few extra conventions. The first paragraph is special: it becomes the summary, shown in lists, search results and autocomplete. After a blank line comes the discussion, with as much detail as needed. After that come structured fields. A complete comment for a function looks like this (read-only; the runner shows the same text parsed in a moment):

Swift
// read-only example: a fully documented function
/// Returns the average of the values.
///
/// An empty array has no average, so the result is `nil`.
/// The sum is computed in `Double`.
///
/// - Parameters:
///   - values: The numbers to average.
///   - scale: A factor applied to the result.
/// - Returns: The scaled mean, or `nil` for an empty array.
/// - Throws: Nothing, but see `scale`.
func average(of values: [Double], scale: Double = 1) -> Double?

The parts, in the order tools expect them:

  1. Summary: one sentence, ending with a period. For a function or method, start with a verb and describe what it does or returns ("Returns the average..."), without repeating the name. For a property or type, use a noun phrase ("The number of items.").
  2. Discussion: details, edge cases, examples, performance. Optional.
  3. - Parameter name: for a single parameter, or - Parameters: followed by an indented list of - name: description lines for several.
  4. - Returns: what the result means, especially for optionals and tuples.
  5. - Throws: which errors can be thrown and when.
  6. Optional callouts (see below).

Seeing what a tool sees

To make the format concrete, here is a miniature documentation reader. It takes the text of a documentation comment, splits the summary, discussion and fields, and prints them the way a tool would collect them. It is deliberately simple (a real tool parses full Markdown), but it uses only ordinary Swift:

Swift A tiny doc-comment parser

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 output is:

TEXT
Summary: Returns the average of the values.
Discussion: An empty array has no average, so the result is `nil`. The sum is computed in `Double`.
Parameter values: The numbers to average.
Parameter scale: A factor applied to the result.
Returns: The scaled mean, or `nil` for an empty array.
Throws: Nothing, but see `scale`.

Notice what the parser needed: the blank /// line to end the summary paragraph, the - Parameters: marker followed by indented items, and the fixed field names (Returns, Throws). Real tools do the same with a full Markdown parser. This is also why the exact spelling of - Parameter and - Returns matters: a typo such as - Return: is simply treated as a bullet in the discussion.

Callouts

Besides the standard fields, you can add callouts: a dash, a keyword and a colon. Xcode and DocC render them as highlighted boxes. The most useful ones are:

Callout Use it for
- Note: Extra information worth reading
- Important: Something the reader must not miss
- Warning: A hazard: data loss, crashes, thread safety
- Precondition: What must be true before the call (documented, not enforced)
- Postcondition: What is true afterwards
- Complexity: Time and memory cost, for example O(n)
- SeeAlso: Related symbols
- Experiment: Suggestions for the reader to try

Use callouts sparingly: if everything is Important, nothing is. The best use is documenting what the type system cannot say, such as complexity, preconditions and threading rules:

Swift Documenting preconditions and complexity

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 first line prints true true false: the third push exceeds the capacity of 2, exactly as the Returns line promises. The second prints Optional(20) Optional(10) nil. Without the comments a reader would have to read the body to learn that a full stack returns false and does not crash; with them the contract is in one place. Note that - Precondition: only documents the rule. The precondition(...) call in the body is what enforces it (Assertions and Preconditions).

Markdown inside comments

Documentation comments accept the usual Markdown: paragraphs, *emphasis*, **bold**, lists, links, and inline code. Fenced blocks give you runnable-looking examples that show up with highlighting:

Swift
// read-only example: Markdown in a comment
/// Returns the sum of two numbers.
///
/// Use it when you want to avoid overflow checks:
///
/// ```swift
/// let total = add(2, 3)   // 5
/// ```
///
/// - Note: For three or more values use `reduce(0, +)`.
func add(_ a: Int, _ b: Int) -> Int { a + b }

Two details are worth knowing. First, code in comments is not compiled, so examples go stale. Keep them short and mirror them in a unit test if the API is important (Testing in Swift). Second, the block form /** ... */ works the same as ///, but most Swift code uses the triple-slash form because it is easier to edit line by line.

Inside DocC, double backticks link to symbols: Rectangle links to a type, Rectangle/area to one of its members, and scaled(by:) to a method with its argument labels. Links are checked when documentation is built, so renaming a symbol produces a warning in the places that mention it. Single backticks are plain inline code with no link, which is what you want for a name that is not a symbol (like a parameter).

DocC: from comments to a website

DocC (the Documentation Compiler) reads documentation comments from a module and produces a browsable website or an archive. It is built into Xcode (Product > Build Documentation) and into the Swift Package Manager through the swift-docc-plugin. DocC and SwiftPM are not available on the runner, so the following is read-only.

Add the plugin to Package.swift:

Swift
// read-only example: Package.swift
// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "Geometry",
    dependencies: [
        .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.4.0")
    ],
    targets: [
        .target(name: "Geometry")
    ]
)

Then build the documentation from the command line:

Terminal
# read-only example: generate and preview the documentation
swift package generate-documentation --target Geometry
swift package --disable-sandbox preview-documentation --target Geometry

For more than API reference you add a documentation catalog: a folder named Geometry.docc next to the sources. Inside it, Geometry.md is the landing page, other Markdown files are articles and tutorials, and images live next to them:

TEXT
Sources/Geometry/
โ”œโ”€โ”€ Rectangle.swift
โ””โ”€โ”€ Geometry.docc/
    โ”œโ”€โ”€ Geometry.md          (landing page with a "Topics" list)
    โ”œโ”€โ”€ GettingStarted.md    (an article)
    โ””โ”€โ”€ Resources/

A landing page groups symbols in a ## Topics section, which is how the standard library's documentation is organized into "Creating an array", "Inspecting an array" and so on:

TEXT
# ``Geometry``

Shapes and measurements for 2D layouts.

## Topics

### Essentials
- ``Rectangle``
- <doc:GettingStarted>

The <doc:GettingStarted> syntax links to an article in the catalog. Hosting is simple: the generated output is a static site that you can publish on any web server or on GitHub Pages.

Compiler-visible notes: MARK, TODO and #warning

Some comments are meant for the people who edit the file, not those who call the code:

  • // MARK: - Section name creates a heading in Xcode's jump bar, which is useful in long files.
  • // TODO: and // FIXME: are highlighted by editors, but the compiler ignores them, so they are easy to forget.
  • #warning("message") makes the compiler print a warning, and #error("message") stops the build. They are good for unfinished code and for unsupported configurations:
Swift #warning makes a reminder impossible to miss

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 program still prints 5, and the compiler adds the warning TODO: handle negative numbers at line 1. In a continuous integration build you can treat warnings as errors, so unfinished markers cannot ship. #error is stronger, and is paired with conditional compilation:

Swift #error stops the build (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 compile fails with error: Linux is not supported by this module, and the program never runs. On a Mac or Windows build the #if block would be skipped and the program would print its message.

What to document and what to skip

  • Document every public symbol. If it is public, it is a promise; a reader should not have to open the implementation to use it.
  • Say what, not how. "Returns the shortest path" belongs in the comment; "uses a priority queue" belongs only if it affects behavior or cost.
  • Do not repeat the name. /// The width. above var width adds nothing. Add units, ranges or invariants: "The horizontal side, in points."
  • Document the surprising parts: optionals returned for empty input, thread-safety rules, errors thrown, performance cliffs, ordering guarantees (for example, Swift's Dictionary order is unspecified).
  • Keep the summary to one sentence and start function summaries with a verb.
  • Update comments with the code. A wrong comment is worse than none. Review diffs for stale docs.
  • Use // for the internals. Private helpers deserve plain comments only when the reason for the code is not obvious.

A good test: cover the code, read only the documentation, and ask whether you could use the API correctly. If not, the comment needs the missing facts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which comment form is a documentation comment attached to the declaration that follows it?

    /// (and the block form /** */) are documentation comments. Plain // and /* */ comments are ignored by documentation tools.
  2. 2. What becomes the summary shown in autocomplete and search results?

    The first paragraph is the summary. A blank line ends it, and the rest becomes the discussion.
  3. 3. What does - Precondition: in a doc comment do?

    Callouts are documentation only. The comment tells readers the rule, and the code has to enforce it.
  4. 4. Which tool turns documentation comments into a browsable website?

    DocC compiles the module's documentation comments and optional catalogs into a static documentation site.
  5. 5. What is the difference between #warning("...") and a // TODO: comment?

    #warning is a compiler directive that produces a real warning, which CI can turn into an error. A TODO comment is just text that editors may highlight.

Summary

  • /// and /** */ are documentation comments; they must sit directly above the declaration and are parsed as Markdown.
  • Start with a one-sentence summary, then a discussion, then - Parameter(s):, - Returns: and - Throws:.
  • Callouts such as - Note:, - Warning:, - Precondition: and - Complexity: document what types cannot say; they do not enforce anything.
  • Double backticks create DocC symbol links that are checked when documentation is built.
  • DocC and the swift-docc-plugin generate websites from comments and .docc catalogs (read-only here).
  • // MARK: organizes files; #warning and #error are real compiler messages, unlike // TODO:.
  • Document every public symbol, describe behavior rather than names, and keep comments in step with the code.

Next: Swift Language Versions and Evolution