Swift Comments

Learn how to write comments in Swift to document and explain your code.

Why Use Comments?

Comments are lines of text in your source code that the Swift compiler completely ignores. They exist purely to help humans — including your future self — understand what a piece of code does, why it exists, or what still needs work.

Single-Line Comments

A single-line comment starts with two forward slashes `//`. Everything after `//` on that line is ignored by the compiler, whether it appears on its own line or at the end of a line of code.

Single-Line Comments

// This program calculates the area of a rectangle
let width = 5
let height = 3

let area = width * height // multiply width by height
print(area) // prints 15

Multi-Line Comments

For longer explanations spanning several lines, Swift supports multi-line comments that begin with `/*` and end with `*/`. Unlike some languages, Swift allows multi-line comments to be nested inside one another.

Multi-Line Comments

/*
 This section handles user input validation.
 It checks that the age is a positive number
 before proceeding with registration.
*/
let age = 20
if age > 0 {
    print("Valid age")
}

Nested Comments

/* Outer comment start
   /* Inner nested comment */
   Outer comment continues and ends here */
print("Nested comments compiled successfully")
  • `//` comments out the rest of the current line
  • `/* ... */` comments out everything between the markers, even across multiple lines
  • Swift uniquely allows nesting `/* */` comments inside each other
  • Comments are often used to temporarily disable code while debugging
  • Good comments explain *why*, not just *what*, since the code already shows what it does
Comment TypeSyntaxTypical Use
Single-line// commentQuick notes, end-of-line explanations
Multi-line/* comment */Longer explanations, temporarily disabling blocks
Nested multi-line/* /* comment */ */Commenting out code that already contains comments
Note: Use comments to explain non-obvious decisions, such as why a particular algorithm was chosen, rather than restating what the code obviously does.
Note: Overusing comments to describe every single line can clutter your code — well-named variables and functions often reduce the need for comments in the first place.

Exercise: Swift Comments

How do you write a single-line comment in Swift?