Swift Documentation
Tags: swift, documentation, ios
Published: 2020-01-07 09:17:04

---
title: Swift Documentation
published: true
date: 2019-11-30 00:00:00 UTC
tags: Swift, Documentation, iOS
canonical_url: https://sarunw.com/posts/swift-documentation/
---

> Any code of your own that you haven't looked at for six or more months might as well have been written by someone else.  
> – Eagleson's Law

When we work with Apple's class and not sure how to use it, we have many ways to find out that information. You can find it in an online document like [Apple Developer Documentation](https://developer.apple.com/documentation/) or you can find in within Xcode.

It comes in many shapes and forms.

## Quick help popover #

You can <kbd>⌥ – Option</kbd> + click on any class to open up quick help like this:

![Quick help](https://sarunw.com/images/documentation-apple.png)<figcaption>Quick help of UIButton</figcaption>

## Symbol inspector Quick Help #

Quick help also shows under the Quick Help inspector panel.

![Symbol inspector Quick Help](https://sarunw.com/images/documentation-quick-help-inspector.png)<figcaption>Quick help of UIButton</figcaption>

## Code completion hint #

When you start typing, Xcode will help you by suggesting a list of a function/property/enum of that class, along with a hint of what they do at the very bottom.

![Function hint](https://sarunw.com/images/documentation-function-autocomplete.png)<figcaption>Short summary of a function showing up in auto-complete</figcaption>

![Property hint](https://sarunw.com/images/documentation-property-autocomplete.png)<figcaption>Short summary of a property showing up in auto-complete</figcaption>

![Enum hint](https://sarunw.com/images/documentation-enum-autocomplete.png)<figcaption>Short summary of an enum showing up in auto-complete</figcaption>

Do you know that we can have these comments for our code too? This article will tell you how.

## Syntax #

Writing documentation for your code is like writing a comment, but with a small syntax change. You need an extra slash for single-line documentation, so instead of two, you need three slashes (///).

```
/// This is your User documentation.
struct User { 
    let firstName: String
    let lastName: String
}
```

For multi-line documentation, you need extra asterisk (\*) in the opening delimiter (/\*\* ... \*/).

```
/** 
    This is your User documentation.
    A very long one.
*/
struct User {
    let firstName: String
    let lastName: String
}
```

## Summary and Discussion #

The above documentation comment will produce a document with a summary part.

![Summary](https://sarunw.com/images/documentation-summary.png)<figcaption>The first paragraph will be used as a documentation summary.</figcaption>

To add a discussion section, what you need to do is write another paragraph. Anything other than the first paragraph will belong in the discussion section.

<aside>
<p>Documentation comments in Swift use Markdown-flavored markup syntax. So when we refer to the paragraph in the document, we mean the paragraph in markdown way.</p>
<p>A paragraph in markdown is one or more consecutive lines of text separated by one or more blank lines.</p>
</aside>

So the example above is a paragraph with two sentences. Which makes them belong in the summary section.

```
/** 
    This is your User documentation. 
    A very long one.
*/
```

If you want the second sentence in the discussion section, make it into another paragraph by adding a new line between those sentences.

```
/** 
    This is your User documentation (This is summary).

    A very long one (This will be shown in the discussion section).
*/
```

You can also use standard markdown in your documentation.

```
/**
 This is your User documentation.
 A very long one.
 
 # Text
 It's very easy to make some words **bold** and other words *italic* with Markdown. You can even [link to Google!](http://google.com)
 
 # Lists
 Sometimes you want numbered lists:

 1. One
 2. Two
 3. Three

 Sometimes you want bullet points:

 * Start a line with a star
 * Profit!

 Alternatively,

 - Dashes work just as well
 - And if you have sub points, put two spaces before the dash or star:
   - Like this
   - And this
 
 # Code
 `` `
 if (isAwesome){
   return true
 }
 `` `
*/
struct User {
    let firstName: String
    let lastName: String
}
```

The above example is valid documentation, which will produce the following quick help.

![Discussion section](https://sarunw.com/images/documentation-discussion.png)<figcaption>The first paragraph of a documentation comment becomes the documentation Summary. Any additional content is grouped into the Discussion section.</figcaption>

Summary and discussion would be enough for documenting a class, property, or simple function. For a complex function, we have a few more sections that we can add.

## Parameters #

For a function with parameters, you can add the parameter section to Quick Help. There are two methods of documenting parameters. A Parameters Section and separate Parameter Fields.

### Separate Parameter Fields #

```
- Parameter x: ...
- Parameter y: ...
```

### Parameters Section #

This declaration style suit for function with many parameters. Using separate Parameter Fields might be a bit repetitive if you have many parameters.

```
- Parameters:
  - x: ...
  - y: ...
  - z: ...
```

## Returns #

For a function with a return value, you can add the return section, like the one you did with parameters.

```
- Returns: ...
```
<aside>
<p>You may specify multiple Returns items at the top level, but only the last one will be shown in Xcode's QuickHelp.</p>
</aside>
## Throws #

The last and the most important one. Since you can't specify error type that will be throw when you declare a function with throws keyword, it is handy to have this information sit right next to that function.

```
- Throws: ...
```

Functions that are marked as Throws should contain the following describing what kind of errors are thrown and in what situations.

```
/// A way that this user greets others.
///
/// Use this method to get the greeting for the user. The person you specify don't affect the way user greet, just the first name, and last name will be used.
/// - Warning: The greeting is always in the caller localization.
/// - Throws:
///     - `MyError.invalidPerson`
///     if `person` is not known by the caller.
///     - `MyError.hardToPronounce`
///     if `person` name is longer than 20 characters.
/// - Parameter person: `User` you want to greet
/// - Returns: A greeting of the current `User`.
func greeting(person: User) throws -> String {
  return "Hello \(person.firstName) \(person.lastName)"
}
```

![Throws](https://sarunw.com/images/documentation-throws.png)<figcaption>Throws section</figcaption>

<aside>
<p>There can be only one Throws delimiter in the comments for a symbol. The behavior for multiple Throws delimiters is undefined.</p>
</aside>
## Auto-generate Quick Help documentation #

Xcode provides an easy way to generate documentation. To use this feature, click on any class, property, function, or part you want to add a document. Then press <kbd>⌥ – Option</kbd> + <kbd>⌘ - command</kbd> + <kbd>/</kbd> or Editor \> Structure \> Add documentation from Xcode's menu. Xcode will generate a document template for you.

```
/// <#Description#>
/// - Parameter person: <#person description#>
```
<aside>
<p>This feature can vary based on your Xcode version. From what I remembered, it used to generate parameters, returns, and throws of the current function, but in Xcode Version 11.1 (11A1027) it only generates parameters.</p>
</aside>
## Extra Fields #

There are many more Callout <sup><a href="#fn1" id="fnref1">[1]</a></sup> that you can add to the documentation. You add Callout with the following syntax:

```
- Callout: description
```

Following are all Callout that you can use:

```
- Attention: ...
- Author: ...
- Authors: ...
- Bug: ...
- Complexity: ...
- Copyright: ...
- Date: ...
- Experiment: ...
- Important: ...
- Invariant: ...
- Note: ...
- Postcondition: ...
- Precondition: ...
- Remark: ...
- Remarks: ...
- Requires: ...
- See: ...
- Since: ...
- Todo: ...
- Version: ...
- Warning: ...
```

The Callout will render in Quick Help under the discussion section as a bold header followed by a block of text.

Here is an example of our `User` documentation with `Warning` callout.

```
/// A way that this user greets others.
///
/// Use this method to get the greeting for the user. The person you specify don't affect the way user greet, just the first name, and last name will be used.
/// - Warning: The greeting is always in the caller localization.
/// - Parameter person: `User` you want to greet
/// - Returns: A greeting of the current `User`.
func greeting(person: User) -> String {
  return "Hello \(person.firstName) \(person.lastName)"
}
```

![Warning Callout](https://sarunw.com/images/documentation-warning.png)<figcaption>Warning Callout</figcaption>

## Conclusion #

It is only a matter of time before your code that once obvious, turns into someone else code. We all know it is not easy and quite a time-consuming task to come up with a good document, but having good documentation will pay off in the long run.

---

*Originally published at https://sarunw.com/posts/swift-documentation/.
Find out my latest article and more at http://sarunw.com I post articles weekly there.*

[![Subscribe](https://thepracticaldev.s3.amazonaws.com/i/rmrsj3km5j19r1ba8tm8.jpg)](https://sarunw.us1.list-manage.com/subscribe/post?u=da8ac0f3b786879a00c413a46&amp;id=43463b63ef&SIGNUP=Devto)

## Related Resources #

- [An extension keywords for documentation comment syntax.](https://github.com/apple/swift/blob/master/docs/DocumentationComments.md)
- [Markup Formatting Reference.](https://developer.apple.com/library/archive/documentation/Xcode/Reference/xcode_markup_formatting_ref/index.html#//apple_ref/doc/uid/TP40016497-CH2-SW1)

* * *
<section>
<ol>
<li id="fn1">
<p><a href="https://developer.apple.com/library/archive/documentation/Xcode/Reference/xcode_markup_formatting_ref/Attention.html#//apple_ref/doc/uid/TP40016497-CH29-SW1" target="_blank" rel="nofollow">https://developer.apple.com/library/archive/documentation/Xcode/Reference/xcode_markup_formatting_ref/Attention.html#//apple_ref/doc/uid/TP40016497-CH29-SW1</a> <a href="#fnref1">↩︎</a></p>
</li>
</ol>
</section>