In Swift, commenting is used in and for three distinct purposes:
- Regular Comments
- Structured Comments for Generating Documentation
- Markup Comments in Playgrounds
Regular Comments
These are the comments that you use to explain the code - either for your own later use or for somebody else maintaining the code later. Proper naming of the variables, constants, methods, classes, functions, etc. by itself provides some kind of explanation/documentation around the code. This self-documenting code is very useful to you or others looking at the code at a later date.
However, lot of times adding some comments would greatly enhance the ability to understand it better — even the readability of the code gets enhanced because the comments punctuate and provide visual separation in the code, which otherwise could be a series of large monotonous blocks.
In Swift, like other languages (C, C++, Java, etc.), there are two ways of commenting:
- Single Line Comments
- Multi-line Comments
Single line comments are preceded with // (two forward slashes). All the text from after that to the end of the line is considered a comment. And the compiler will completely ignore that text during the compilation of the code.
var score = 0
var level = 1
…
…
// Each level gives 100 base points
score = level * 100
…
…
score += 5 // 5 points for the move
Multi-line comments are written in between /* and */ - as name implies there can be multiple lines of comments in between them. In Swift, you can also nest these multi-line comments. Meaning /* … /* … */ …*/ is valid and does not mess up the code (as it does in some other languages). This ability to nest multi-line code provides an easy way to comment out code blocks that might already contain multi-line comments.
/*
Takes two integers as parameters.
And returns their sum.
*/
fun add(a: Int, _ b: Int) -> Int {
return a+b
}
let sum = add(5, 10)
In Swift, that above code can be completely commented out again with /* */ without worrying about the multi-line comments that are already there.
/*
/*
Takes two integers as parameters.
And returns their sum.
*/
fun add(a: Int, _ b: Int) -> Int {
return a+b
}
let sum = add(5, 10)
*/
In Xcode, you can select a section of the code and press Command-/ to comment out that entire selection. On that selection, you can use Command-/ again to uncomment. You can also use the menu item Editor-Structure-Comment Selection to comment/uncomment like above. This comments out all the lines in the selection individually by placing // at the start of the line.
Structured Comments for Generating Documentation
While // and /* */ add some additional context and explanation to the code, no additional documentation can be generated out of it. This won’t show up in the Quick Help windows of Xcode or Playground.
By using the Structured Documentation Comments as described below, if you place the cursor on the var/func of your interest, help will show up in the Quick Help Inspector. You can also get the Quick Help window by Option-Clicking the variable or function or method of your interest.
extension UIColor {
/// Takes RGB values in decimal and returns UIColor.
/// ```
/// let gameGreen = UIColor.color(70, 145, 70)
/// ```
/// - parameter red: A decimal float (e.g. 70)
/// - parameter green: A decimal float (e.g. 145)
/// - parameter blue: A decimal float (e.g. 70)
/// - returns: A UIColor object with specified RGB and alpha 1.0
class func color(red: CGFloat, _ green: CGFloat, _ blue: CGFloat) -> UIColor {
return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: 1.0)
}
}
There are two ways to add the structured documentation comments:
- /// (three forward slashes followed by the comment)
- Embedding the comments in /** and */
In the above example, the description follows the first /// and below, there is information about parameters and return values. In addition to the parameter and returns values, you can use several other keywords to more thoroughly describe other aspects of a method or function.
- - parameter <parameter name>:
- - returns:
- - throws:
- - Authors:
- - Note:
- - Warning:
- - SeeAlso:
- ``` <code/example usage> ```
There is a large list of tokens that can be used in Swift documentation. Description does not require any token — you will start out the comment with the description. You will use this structured commenting in documenting API. This way, the methods available for public use will have comment coming right from the code. In a typical app code, you can use this style to comment the methods that are used elsewhere (or, comment all the classes and methods this way — at least with the description fields)
extension UIColor {
/**
Takes RGB values in decimal and returns UIColor.
```
let gameGreen = UIColor.color(70, 145, 70)
```
- parameter red: A decimal float (e.g. 70)
- parameter green: A decimal float (e.g. 145)
- parameter blue: A decimal float (e.g. 70)
- Returns: A UIColor object with specified RGB and alpha 1.0
*/
class func color(red: CGFloat, _ green: CGFloat, _ blue: CGFloat) -> UIColor {
return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: 1.0)
}
}
The above comment embedded inside /** */ also produces the same Quick Help, etc. as above. Code and example usage can be embedded in between two ```
You can also do additional markup. Following are some typical formatting tokens:
- # for H1 (Header 1)
- ## for H2
- ### for H3
- * for lists
- 1, 2, 3, … for numbered lists
While the /** */ format seems cleaner, you will see a lot of usage of /// as well. This tags each line as a comment - and that’s probably better if you are looking at the code without color coding.
Markup Comments in Playgrounds
Markup can be rendered beautifully in Playgrounds by using a special syntax in comments. If you embed the comments in //: (for single line) or /*: */ (for multi-line), these comments can be rendered right in the Playgrounds (by using menu item: Editor - Show Rendered markup)
//: ### Function for adding integers.
//: Takes two integers and adds them and returns an integer.
//: * a - first integer
//: * b - second integer
func add(a: Int, _ b: Int) -> Int {
return a+b
}
As you can see above, the heading is rendered as H3. And there is a bullet point list, because * is used in front of a series of items.
The above code is exactly the same as the one below - here the markup is placed inside multi-line markup tags.
/*:
### Function for adding integers.
Takes two integers and adds them and returns an integer.
* a - first integer
* b - second integer
*/
func add(a: Int, _ b: Int) -> Int {
return a+b
}