{infiniteZest}
// Articles. Tutorials. Utilities.
Home  |   Search  |   Login  
Categories Skip Navigation Links
New / All
AJAX
Apple
ASP.NET
.NET
Git
Google / Android
Python / IronPython
Miscellaneous
SQL Server
Swift - Comments and Header Docs
Summary
This article discusses code commenting for various purposes, including generating documentation.
 
Table of Contents

Regular Comments

Structured Comments for Generating Documentation

Markup Comments in Playgrounds

 
Article Series
Previous Article:
Test Your Knowledge: Swift - Variables and Constants
This article is part of the Series:
Swift - Introduction and Basics
Next Article:
Test Your Knowledge: Swift - Comments and Header Docs

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
}

Take a Quick Quiz on this Article

1. Which of the following are true in Swift?



: Same as C, C++, and Java
Question 1 of 5
Article Series
Previous Article:
Test Your Knowledge: Swift - Variables and Constants
This article is part of the Series:
Swift - Introduction and Basics
Next Article:
Test Your Knowledge: Swift - Comments and Header Docs
Bookmark and Share This

More Articles With Similar Tags
icon-swift-test.jpg
Test on comments, structured comments, and markup in Swift
icon-swift-article.jpg
Tags: bool, types, swift
This article discusses the boolean types in Swift and contrasts with how these types are used in C and Objective-C.
icon-swift-test.jpg
Tags: bool, types, swift
Test on Boolean Types in Swift.
icon-swift-article.jpg
This article talks about unwrapping the optionals in Swift implicitly and the circumstances where you would use this functionality.
icon-swift-article.jpg
This article discusses the safer ways of unwrapping an optional in Swift that includes Optional Binding.
About  Contact  Privacy Policy  Site Map