Swift Comments

Swift Comments

Comments are text in your code that the Swift compiler completely ignores.

They are used to explain what the code does, leave notes for yourself, or temporarily disable parts of your code.

Writing good comments is considered a best practice in software development.

Swift supports two types of comments: single-line comments and multi-line comments.


Single-Line Comments

Single-line comments start with two forward slashes //.

Any text that follows the // on that specific line will be ignored by the compiler.

Single-Line Comment Example:

// This is a single-line comment
print("Hello, World!") // This comment is at the end of a code line

You can place single-line comments on their own line, or at the end of a line of code.


Multi-Line Comments

If you have a lot to explain, you can use a multi-line comment.

Multi-line comments start with /* and end with */.

Everything between these two markers will be ignored by the compiler, no matter how many lines it spans.

Multi-Line Comment Example:

/* 
This is a multi-line comment.
It can span across several lines.
Useful for long explanations or documentation.
*/
print("Comments are useful!")

Nested Multi-Line Comments

A unique and powerful feature of Swift is that you can nest multi-line comments inside other multi-line comments.

This makes it incredibly easy to comment out large blocks of code, even if those blocks already contain multi-line comments!

Nested Comments:

/* Outer comment start
    /* Inner comment */
Outer comment end */

Many other languages, like C and Java, do not support nested multi-line comments.


Exercise

Which symbols are used to create a single-line comment in Swift?