Writing comments in Swift code is a little different from writing comments in Objective-C code. We can still use the double slash // for single-line comments and the /** and */ for multiline comments; however, if we want to use the comments to also document our code, we need to use the triple slash (///) or multiline comment block.
Xcode will also auto-generate a comment template based on your signature of the method/function by highlighting it and pushing command + option+ / together.
To document our code, we generally use fields that Xcode recognizes. These fields are as follows:
- Parameter: When we start a line with parameter {param name}:, Xcode recognizes this as the description of a parameter
- Return: When we start a line with return:, Xcode recognizes this as the description of the return value
- Throws: When we start a line with throws:, Xcode recognizes this as the description of any errors that this method may throw
The following playground shows examples of both single-line and multiline comments and how to use the comment fields:
To write good comments, I would recommend using single-line comments within a function to give quick one-line explanations of your code. We then use multiline comments outside functions and classes to explain what the function and class do. The preceding playground shows a good way to use comments. By using proper documentation, as we did in the preceding screenshot, we can use the documentation feature within Xcode. If we hold down the option key and then click on the function name anywhere in our code, Xcode will display a popup with the description of the function.
The following screenshot shows what that popup would look like:
We can see that the documentation contains five fields. These fields are as follows:
- Declaration: This is the function's declaration.
- Description: This is the description of the function as it appears in the comments Parameters. The parameter descriptions are prefixed with the Parameters: tag in the comment section.
- Throws: The throws description is prefixed with the Throws tag and describes what errors are thrown by the methods.
- Returns: The return description is prefixed with the Returns: tag in the comment section.
- Declared In: This is the file that the function is declared in so that we can easily find it.
There are significantly more fields that we can add to our comments. You can find the complete list on Apple's site: https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_markup_formatting_ref/MarkupFunctionality.html.
If you are developing for the Linux platform, I would still recommend using Apple's documentation guidelines because, as other Swift IDEs are developed, I believe they will support the same guidelines.