Swift Comments

By

Learn how to write comments in Swift, including single-line comments, multi-line comments, and the handy ability to nest multi-line comments together.

~~~

This tutorial belongs to the Swift series

A comment in Swift can take 2 forms: a single-line comment, and a multi-line comment.

Comments are text the compiler ignores. We use them to explain why a piece of code exists, to leave notes for our future selves, or to disable some code while debugging.

A single-line comment starts with //:

//this is a comment

and it can be put at the end of a line of code:

let a = 1 //this is a comment

Everything from the // to the end of the line is ignored.

A multi-line comment is written using this syntax:

/* this
 is
    a multi-line
 comment
*/

Everything between /* and */ is ignored, no matter how many lines it spans.

Nesting multi-line comments

Swift allows you to nest multi-line comments:

/* this
 is
    a /* nested */ multi-line
 comment
*/

which is handy especially when commenting out large portions of code that already contains multi-line comments.

This is a nice difference from C or JavaScript. In those languages the first */ closes the comment, so wrapping code that already has a multi-line comment breaks the program. In Swift, each /* needs its own */, and the compiler keeps count.

That’s also the one pitfall to remember. If a /* inside the block has no matching */, the comment never ends, and the compiler complains about the code that follows. Balance every /* with a */ and you’re fine.

Documentation comments

There’s a third form worth knowing: documentation comments. Write them with three slashes right above a function, a type or a property:

/// Returns the price including 22% VAT.
func priceWithVAT(price: Double) -> Double {
    price * 1.22
}

Xcode picks them up and shows them in Quick Help when you option-click the symbol. You can use Markdown inside them, so lists and code samples work too.

I also use // MARK:, // TODO: and // FIXME: comments. Xcode lists them in the jump bar at the top of the editor, so they double as navigation aids in long files.

Tagged: Swift · All topics
~~~

Related posts about swift: