Swift Standard Documentation Comment

How to use Swift documentation comments

This answer was last revised for Swift 5.7 and Xcode 14.x.


DocC is Apple's documentation compiler that takes comments (plus additional resources) and produces rich documentation that can be viewed in Xcode or hosted on web.

Writing Documentation

Type /// or /** */ to begin a documentation comment and then use DocC's special dialect of Markdown to write the content. This dialect supports many keywords like - Parameters: for describing function arguments or - Returns: for describing return values.

Note how the > Warning: keyword was recognized as an aside and automatically emphasized. DocC supports multiple other aside types like Note, Tip and Important.

/// Produce a greeting string for the given `subject`.
///
/// ```
/// print(hello("world")) // "Hello, world!"
/// ```
///
/// > Warning: The returned greeting is not localized. To
/// > produce a localized string, use ``localizedHello(_:)``
/// > instead.
///
/// - Parameters:
/// - subject: The subject to be welcomed.
///
/// - Returns: A greeting for the given `subject`.
func hello(_ subject: String) -> String {
return "Hello, \(subject)!"
}

Sample Image

Linking to Symbols

DocC will automatically link (and auto-complete!) symbols wrapped in double backticks ``. You can link to related symbols in the same type or other types in the same module.

Note that linking is limited only to public symbols and only to one module. As of today, there's no way to type e.g. ``UIView`` and have DocC automatically link it to UIKit's documentation.

Generating Webpages

DocC supports exporting your documentation into webpages. First, you need to compile your documentation by choosing Product → Build Documentation. Once the documentation is built, export its archive by clicking the More button. The archive will contain the entire documentation webpage that you can then host on your server.

The above process is a bit complicated, so there are many tools that can help you automate it. Apple offers swift-docc-plugin that you can add to your Swift package or Xcode project and configure it to run on every build. You can automate this process on CI as well.

Further Reading

I recommend reading the following guides to learn more about DocC:

  • Writing Symbol Documentation in Your Source Files
  • Formatting Your Documentation Content
  • Adding Structure to Your Documentation Pages
  • Distributing Documentation to External Developers

Does Swift have documentation generation support?

Documentation comments are supported natively in Xcode, producing smartly rendered documentation in Quick Help (both in the popover when -clicking symbols, and in the Quick Help Inspector ⌥⌘2).

Symbol documentation comments are now based on the same Markdown syntax used by rich playground comments, so a lot of what you can do in playgrounds can now be used directly in source code documentation.

For full details of the syntax, see Markup Formatting Reference. Note that there are some discrepancies between the syntax for rich playground comments & symbol documentation; these are pointed out in the document (e.g. block quotes can only be used in playgrounds).

Below is an example and a list of the syntax elements that currently work for symbol documentation comments.


Updates

Xcode 7 beta 4 ~ Added "- Throws: ..." as a top-level list item which appears alongside parameters and return descriptions in Quick Help.

Xcode 7 beta 1 ~ Some significant changes to syntax with Swift 2 - documentation comments now based on Markdown (same as playgrounds).

Xcode 6.3 (6D570) ~ Indented text is now formatted as code blocks, with subsequent indentations being nested. It doesn't appear to be possible to leave a blank line in such a code block - trying to do so results in the text being tacked onto the end of the last line with any characters in it.

Xcode 6.3 beta ~ Inline code can now be added to documentation comments using backticks.


Example for Swift 2

/// Text like this appears in "Description".
///
/// Leave a blank line to separate further text into paragraphs.
///
/// You can use bulleted lists (use `-`, `+` or `*`):
///
/// - Text can be _emphasised_
/// - Or **strong**
///
/// Or numbered lists:
///
/// 7. The numbers you use make no difference
/// 0. The list will still be ordered, starting from 1
/// 5. But be sensible and just use 1, 2, 3 etc…
///
/// ---
///
/// More Stuff
/// ==========
///
/// Code
/// ----
///
/// Use backticks for inline `code()`. Indentations of 4 spaces or more will create a code block, handy for example usage:
///
/// // Create an integer, and do nothing with it
/// let myInt = 42
/// doNothing(myInt)
///
/// // Also notice that code blocks scroll horizontally instead of wrapping.
///
/// Links & Images
/// --------------
///
/// Include [links](https://en.wikipedia.org/wiki/Hyperlink), and even images:
///
/// ![Swift Logo](/Users/Stuart/Downloads/swift.png "The logo for the Swift programming language")
///
/// - note: That "Note:" is written in bold.
/// - requires: A basic understanding of Markdown.
/// - seealso: `Error`, for a description of the errors that can be thrown.
///
/// - parameters:
/// - int: A pointless `Int` parameter.
/// - bool: This `Bool` isn't used, but its default value is `false` anyway…
/// - throws: A `BadLuck` error, if you're unlucky.
/// - returns: Nothing useful.
func doNothing(int: Int, bool: Bool = false) throws -> String {
if unlucky { throw Error.BadLuck }
return "Totally contrived."
}

Swift Documentation Quick Help


Syntax for Swift 2 (based on Markdown)


Comment Style

Both /// (inline) and /** */ (block) style comments are supported for producing documentation comments. While I personally prefer the visual style of /** */ comments, Xcode's automatic indentation can ruin formatting for this comment style when copying/pasting as it removes leading whitespace. For example:

/**
See sample usage:

let x = method(blah)
*/

When pasting, the code block indentation is removed and it is no longer rendered as code:

/**
See sample usage:

let x = method(blah)
*/

For this reason, I generally use ///, and will use it for the rest of the examples in this answer.


Block Elements

Heading:

/// # My Heading

or

/// My Heading
/// ==========



Subheading:

/// ## My Subheading

or

/// My Subheading
/// -------------



Horizontal rule:

/// ---



Unordered (bulleted) lists:

/// - An item
/// - Another item

You can also use + or * for unordered lists, it just has to be consistent.



Ordered (numbered) lists:

/// 1. Item 1
/// 2. Item 2
/// 3. Item 3



Code blocks:

///    for item in array {
/// print(item)
/// }

An indentation of at least four spaces is required.


Inline Elements

Emphasis (italics):

/// Add like *this*, or like _this_.



Strong (bold):

/// You can **really** make text __strong__.

Note that you cannot mix asterisks (*) and underscores (_) on the same element.



Inline code:

/// Call `exampleMethod(_:)` to demonstrate inline code.



Links:

/// [Link Text](https://en.wikipedia.org/wiki/Hyperlink)



Images:

/// ![Alt Text](http://www.example.com/alt-image.jpg)

The URL can be either a web URL (using "http://") or an absolute file path URL (I can't seem to get relative file paths to work).

The URLs for links and images can also be separated from the inline element in order to keep all URLs in one, manageable place:

/// A [link][1] an an ![image][2]
///
/// ...
///
/// [1]: http://www.example.com
/// [2]: http://www.example.com/image.jpg


Keywords

In addition to the Markdown formatting, Xcode recognises other markup keywords to display prominently in Quick Help. These markup keywords mostly take the format - <keyword>: (the exception is parameter, which also includes the parameter name before the colon), where the keyword itself can be written with any combination of uppercase/lowercase characters.

Symbol Section keywords

The following keywords are displayed as prominent sections in the help viewer, below the "Description" section, and above the "Declared In" section. When included, their order is fixed as displayed below even though you can include them in whatever order you like in your comments.

See the fully documented list of section keywords and their intended uses in the Symbol Section Commands section of the Markup Formatting Reference.

/// - parameters:
/// - <#parameter name#>:
/// - <#parameter name#>:
/// - throws:
/// - returns:

Alternatively, you can write each parameter this way:

/// - parameter <#parameter name#>:

Symbol Description Field keywords

The following list of keywords are displayed as bold headings in the body of the "Description" section of the help viewer. They will appear in whatever order you write them in, as with the rest of the "Description" section.

Full list paraphrased from this excellent blog article by Erica Sadun. Also see the fully documented list of keywords and their intended uses in the Symbol Description Field Commands section of the Markup Formatting Reference.

Attributions:

/// - author:
/// - authors:
/// - copyright:
/// - date:

Availability:

/// - since:
/// - version:

Admonitions:

/// - attention:
/// - important:
/// - note:
/// - remark:
/// - warning:

Development State:

/// - bug:
/// - todo:
/// - experiment:

Implementation Qualities:

/// - complexity:

Functional Semantics:

/// - precondition:
/// - postcondition:
/// - requires:
/// - invariant:

Cross Reference:

/// - seealso:

 Exporting Documentation

HTML documentation (designed to mimic Apple's own documentation) can be generated from inline documentation using Jazzy, an open-source command-line utility.

$ [sudo] gem install jazzy
$ jazzy
Running xcodebuild
Parsing ...
building site
jam out ♪♫ to your fresh new docs in `docs`

Console example taken from this NSHipster article

Auto generate method comment in Xcode

You can use the Code Snippets library for this. It won't automatically generate placeholders for each parameter, but it's pretty useful nonetheless. Here's what you do:

  1. Write out a sample comment block in your code somewhere.
  2. Insert <#xyz#> where you want a placeholder named 'xyz' to appear. (These are like parameter completion placeholders, so you can tab between them and overwrite them.)

For example:

/**
* Method name: <#name#>
* Description: <#description#>
* Parameters: <#parameters#>
*/
  1. Open up the right hand sidebar. In the bottom pane click on the two curly braces icon to bring up the snippets library.
  2. Select and drag your text to the code snippets library.
  3. It'll create a new one. Double click on it, click edit in the popup, and give it a completion shortcut (e.g. comblk for comment block.)

Now, when you type 'comblk' anywhere in your editors, the autocomplete popup appears and you can hit return to paste in the snippet. The first placeholder will be selected and you can start typing the method's name. Hit tab to switch to description, and so on.

Not ideal but it's better than nothing. Snippets are a nice idea that Apple haven't quite finished implementing yet.

Xcode 8 auto-generated quick help documentation

This refers to Xcode 8 (and later) feature, where you can select a method like this:

func foo(bar: Int) -> String { ... }

... and then press +option+/ (or choose “Structure” » “Add documentation” from Xcode's “Editor” menu) and it will generate the following comments template for you:

/// <#Description#>
///
/// - parameter bar: <#bar description#>
///
/// - returns: <#return value description#>

It just facilitates the writing of documentation for Quick Help.


Note, while this behavior has changed a bit over time, Xcode can be particular about where the cursor must be when you attempt to do this. For example, the cursor has to be somewhere in the function name, foo in my above example, for this to work. Or just double click on the function name and then press +option+/


You asked whether this feature replaces tools like Jazzy.

No, it doesn’t replace Jazzy or similar tools. Amongst other things, Jazzy creates stand-alone HTML documentation from this inline documentation. So, it is simply a question of whether you need these stand-alone outputs from Jazzy for any reason. If so, use Jazzy (or similar tool) in conjunction with this integrated documentation. If not (i.e., you are only looking for documentation from within the Xcode IDE), then Jazzy is not needed.

Swift documentation: instance/type property/method notation

Unfortunately Swift does not have an official or widely-accepted notation to distinguish type properties/methods and instance properties/methods with type name prefixed form.

(So, usual Swift programmers (even expert) cannot understand what you are asking.)

Type name prefixed form is actually used in the Swift book, but not so often.

As far as I checked:

  • In some parts, type property is referred to in a form like UInt32.max, but as you see this is just using actual notation valid as Swift expression.

  • In some other parts, type method is referred to as a form like LevelTracker.unlock(_:), but this also is a valid expression in Swift and I'm not sure Apple is using this as a documentation notation for type method. I cannot find an example in the Swift book with a short glance, but initializers are often referred to in a form like String.init(data:encoding:) and this is also a valid expression in Swift.

  • For other cases, instance methods or properties are referred to as instanceVar.methodName(_:) or instanceVar.propertyName, of course instanceVar appears in a nearby code snippet and is not a type name, this actually is not what you are looking for.

And as you already know, in Apple's official references, methods or properties are shown with heading Instance method, Type method , Instance Property or Type Property. Or prefixed with class/static var/let, class/static func, var/let or func.

I cannot find an example with a very short survey, but some articles (including Apple's) may be referring to an instance method also in a form TypeName.methodName(_:) (or instance property as well.) Seems Swift community thinks distinguishing type members and instance members is not important.

I could not take much time, but seems it is obvious that

Swift does not have an official or widely-accepted notation to distinguish type properties/methods and instance properties/methods with type name prefixed form.

Maybe you need to write something like instance method Array.append(_:) to represent Array#append(_:).

(To note, Array.append(_:) is also a valid expression in Swift.)

Is it possible to use images in swift documentation in Xcode?

No, you can't include images for standard Swift documentation except Playgrounds. For playgrounds, you can check these links Add resources to a playground, Images.

How to create own code completion description in swift

Precede the variable declaration with a three-slash comment. Like this:

Sample Image



Related Topics



Leave a reply



Submit