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 15Multi-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
Exercise: Swift Comments
How do you write a single-line comment in Swift?