Does Swift have documentation generation support?
Asked Answered
M

13

255

Many languages support documentation comments to allow a generator (like javadoc or doxygen) to generate code documentation by parsing that same code.

Does Swift have any type documentation comment feature like this?

Mills answered 4/6, 2014 at 21:34 Comment(5)
Knowing that Xcode with objective-c allows documentation comments, I believe that Apple will add this option to Xcode with swift in the near future (however, it's only a supposition, I have no evidence)Ayres
@Δdeveloper I was supposing the same, but as I haven't seen any reference I was wondering if someone can confirm it and also if there will be any specific documentation tool.Mills
They'll definitely add something in the future, the // MARK: comment is also scheduled for a future Xcode version.Soler
Doxygen-style comments kind-of work for class methods, with ~several~A LOT OF caveats. I for one will just keep using the Doxygen style (like I did for Obj-C) and hope Xcode improves its support for those.Misteach
For documenting block parameters, see https://mcmap.net/q/111435/-how-can-i-properly-document-a-method-with-a-completion-handler-in-ios-swiftLoveinamist
R
414

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

Recondition answered 20/2, 2015 at 16:39 Comment(12)
Looks like the behaviour changed in the final version of Xcode 6.3 (6D570). The indented blocks are now formatted as blocks of code and can be nested with more than two levels.Tager
Very nice description of Swift 2.0 documentation syntax. You should update the post to include the /// - todo: keywordDictum
@LeonardoFaoro Thanks, good find. I suspect there are still more of these keywords and they seem to be undocumented, so I welcome any suggestions!Recondition
It's actually based on reStructuredText not markdownTeledu
@Teledu Actually no. It may have been based on reStructuredText previously, but as of Xcode 7 documentation comments are based on Markdown, with the same basic format as playground comments. See the Xcode 7 Release Notes for details.Recondition
Good information; but (quite annoyingly!) neglects to mention how you actually generate re-distributable documentation from code marked-up in this way. Will the 'Quick Help Inspector' docs be build into a .framework, for example? An edit would be much appreciated :-)Admonition
@ChrisHatton Fair point. Inline documentation comments are not automatically compiled into a docset when building a framework. I have added an edit at the bottom pointing to a tool that can be used to export documentation.Recondition
Is there a way to link to other functions in the same file, like JavaDoc does? For instance, "see myOtherMethod(param1:) for extended functionality"Oversew
Swift version of - parameter is case sensitive! The proper use as of XCode 8.3 is /// - Parameter name: description Sesqui
@BenLeggiero, yes, by using /// - Tag: otherMethod and [otherMethod](x-source-tag://otherMethod). For more details, see my answer.Poop
@ClayEllis That doesn't seem to work in Xcode. The - Tag: version doesn't show up in Quick Help. Although the link version does appear in Quick Help, when clicked, it does nothing.Oversew
@BenLeggiero I’ve noticed that it’s intermittent. I don’t always see Xcode successfully follow the link. However, it is a feature and does work with some rate of success lower than 100%. - Tag: isn’t supposed to show up in Quick Help’s list of attributes. It’s a non-user-facing meta tag.Poop
P
58

Here are some things that work for documenting swift code in Xcode 6. It is very buggy and sensitive to colons, but it's better than nothing:

class Foo {

    /// This method does things.
    /// Here are the steps you should follow to use this method
    ///
    /// 1. Prepare your thing
    /// 2. Tell all your friends about the thing.
    /// 3. Call this method to do the thing.
    ///
    /// Here are some bullet points to remember
    ///
    /// * Do it right
    /// * Do it now
    /// * Don't run with scissors (unless it's tuesday)
    ///
    /// :param: name The name of the thing you want to do
    /// :returns: a message telling you we did the thing
    func doThing(name : String) -> String {
        return "Did the \(name) thing";
    }
}

The above is rendered in Quick Help as you would expect with formatted numeric lists, bullet points, parameter and return value documentation.

None of this is documented - file a Radar to help them along.

Paphian answered 23/7, 2014 at 20:3 Comment(5)
Mattt Thompson wrote an article about this, and he thinks this is reStructuredText.Consider
In the above example, The plus (+) and minus (-) symbols will also act as bullet points, in addition to the asterisks shown.Phosphene
It seems that a blank comment (///) line is required between any explanatory text and the :param: or :returns: lines. Omitting this causes XCode (6.1.1 at time of writing) to include the parameter help in the main body of the function description.Sinuate
Unfortunatelly this doesn't work with Xcode 7 Beta. Hopefully they will fix it in a release version.Bowker
Xcode 7 adopted a different syntax: ericasadun.com/2015/06/14/swift-header-documentation-in-xcode-7Acapulco
G
42

New in Xcode 8, you can select a method like this

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

Then press command + 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#>
Gender answered 18/10, 2016 at 18:12 Comment(1)
Thanks for this. I'll just mention that the keyboard shortcut you indicate doesn't seem to work on a Danish keyboard, where "/" is shift-"7".Apiculture
B
27

Swift includes "///" comment handling (although probably not everything yet).

Write something like:

/// Hey!
func bof(a: Int) {

}

Then option-click on the func name and voilà :)

Bates answered 13/6, 2014 at 10:15 Comment(0)
G
11

I can confirm that ShakenManChild has provided peopr solution

Just make sure, you have an empty line below the description!

An invalid situation

Proper way

Another way

Another commenting style

Grow answered 22/11, 2014 at 14:52 Comment(0)
A
8

Yes. Base common (I made snippets for it with Obj-C equivalent)

Objective-C:

/**
 @brief <#Short description - what it is doing#>

 @discussion <#Description#>

 @param  <#paramName#> <#Description#>.

 @return <#dataType#> <#Description#>.
 */

Swift

/**
<#Short inline description - what it is doing#>

<#Description#>

:param:  <#paramName#> <#Description#>.

:returns: <#dataType#> <#Description#>.
*/
Anisometric answered 28/7, 2015 at 20:25 Comment(0)
B
8

In Xcode Editor -> Structure -> Add Documentation.

enter image description here

Bonney answered 5/2, 2017 at 11:58 Comment(1)
Yes, it has been mentioned more than 3 months ago by Logan Jahnke.Diver
R
7

If you're only using Swift then Jazzy is worth looking at.

https://github.com/realm/jazzy

Reprisal answered 11/3, 2015 at 12:9 Comment(1)
VVDocumenter is also very useful to use alongside Jazzy. github.com/onevcat/VVDocumenter-XcodeReprisal
S
6

I've found something interesting, digging in the Xcode binary. Files with the ending .swiftdoc. It definitely has docs, because these files contain the docs for the Swift UIKit / Foundation API, unfortunately it seems to be a proprietary file format, for use in the Documentation viewer in Xcode.

Soler answered 6/6, 2014 at 10:40 Comment(0)
W
1

Swift 5.6+ provides rich API reference documentation and interactive tutorials generation with DocC ⇗. The Swift-DocC Plugin ⇗ provides commands for the Swift Package Manager that supports building documentation for SwiftPM libraries and executables.

Package.swift

    dependencies: [
        // other dependencies
        .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
    ],

Terminal:

swift package generate-documentation
swift package plugin generate-documentation --help

Resources

Blog: Swift.org

Documentation: Archived

Sample Code

WWDC Sessions


Syntax Compendium

Key elements and heading words as currently supported.

/// This text appears in the top **Summary** section.
/// These top lines appears before the **Declaration** heading.
/// 
/// - Author: Firstname Lastname
/// - Version: 0.1
/// 
/// Leave a blank line to separate further text into paragraphs.
/// 
/// | key   | value |
/// |-------|-------|
/// | abc   | 123   |
/// 
/// Example code block:
/// 
/// ``` swift
/// // Create an integer, and do nothing with it
/// let myInt = 42
/// doNothingReally(myInt)
/// ```
/// 
/// Bulleted lists can use `-`, `+` or `*`:
/// 
/// - Text can be *emphasised*
/// - Or **strong**
/// - You can use backticks for `code(012)` 012
/// 
/// Lists can be numbered:
/// 
/// 1. The numbers you use make no difference
/// 2. The list will still be ordered
/// 3. But be sensible and just use 1, 2, 3 etc…
///
/// - See Also: [DocD Reference](https://www.swift.org/documentation/docc/)
/// - See Also: <https://www.swift.org/documentation/docc/>
///
/// - Date: 2023.05.12
/// - Copyright: @whomever
/// - Experiment: This may or may not work as expected.
/// - Invariant: `xyz` will not change during execution
/// - Attention: Look here!
/// - Note: Whether the weather be fine, or whether the weather be…
/// - Postcondition: `address` will be updated
/// - Precondition: `person` must be non-nil
/// - Remark: This is remarkable.
/// - Requires: `Contacts` framework
/// - Requires: macOS version 12 or better 
/// - Since: The Beginning Of Time
/// - Todo: Just one more task
/// - Tip: Lorem ipsum
/// - Warning: warning, warning
///
/// - Important: This needs to be read.
///
/// - Throws: nothing
/// 
/// - Parameters:
///   - int: A pointless `Int` parameter.
///   - bool: This `Bool` isn't used, but its default value is `false`  anyway…
/// 
/// - Returns: Nothing useful.
func doNothingReally(int: Int, bool: Bool = false) -> String {
    return "Totally contrived."
}

At the time of this writing See Also: works ok. However, SeeAlso: is not working pending the general release of Support legacy - SeeAlso: callout asides #461

Wristband answered 13/5, 2023 at 2:0 Comment(0)
P
0

Jazzy can help to generate beautiful apple styled documentation. Here is a sample app with details on how to use and configure quickly.

https://github.com/SumitKr88/SwiftDocumentationUsingJazzy

Philoctetes answered 8/12, 2019 at 11:14 Comment(0)
A
-1

Maybe it's a good idea to have an eye on AppleDoc or Apple's own HeaderDoc which isn't recognized very much. I can still find some HeaderDoc hints in 10.9 Mavericks terminal (headerdoc2html)

I recommend to read the latest "What's New In Xcode"* (not sure if it's still under NDA) *The link points to the Xcode 5.1 version wich contains infos about HeaderDoc too.

Artilleryman answered 18/6, 2014 at 15:47 Comment(0)
D
-1

As of Xcode 5.0, Doxygen and HeaderDoc structured comments are supported.

Source

Danitadaniyal answered 9/7, 2014 at 22:5 Comment(7)
Well, I was asking about Swift in this case.Mills
@Mills Are you using Swift in Xcode? Then yes.Danitadaniyal
Matt, from what I know (I may be wrong) Swift it's not supported until Xcode 6 beta, so I'm not sure if the documentation for Xcode 5 it is valid for Xcode 6 (and for then Swift)Mills
@Mills It works. I've been using the same style doxygen documentation as I did in Objective-C and it works. Above a method or property, I use /// This is what the method does. etc.Danitadaniyal
Ok, then the thing is that you have tested it on Xcode 6. I was confused because you were talking about Xcode 5 and the link is for Xcode 5Mills
@Mills Built-in support for documentation like this was first included in Xcode (Objective-C). Xcode 6 brings in Swift. Xcode still handles documentation just the same.Danitadaniyal
This is not true. Doxygen and HeaderDoc structured comments are not supported in Swift. Yes, you can have \\\ or \** comments, but it doesn't conform to Doxygen/HeaderDoc structure beyond that. The keyword syntax is different.Cowardice

© 2022 - 2024 — McMap. All rights reserved.