Swift Comments
Comments are notes for humans. The compiler ignores them completely, so you can use them to explain why code exists, to leave reminders, or to switch off a line temporarily while testing.
Single-line comments
Two slashes // start a comment that lasts until the end of the line. It can stand on its own line or follow code:
// Calculate the total price of an order
let unitPrice = 12
let quantity = 3
let total = unitPrice * quantity // 36
print(total)36
Multi-line comments
Text between /* and */ is a comment, however many lines it spans:
/*
This program prints a short countdown.
It was written for the Comments chapter.
*/
print(3)
print(2)
print(1)
print("Lift-off!")3
2
1
Lift-off!
Nested comments
Unlike C, Java or JavaScript, Swift allows nested multi-line comments. That makes it safe to comment out a big block of code that already contains /* … */ comments:
/*
print("This line is disabled")
/* an inner comment that would end the outer one in C */
print("This one too")
*/
print("Only this line runs")Only this line runs
Commenting out code
A common trick while debugging is to put // in front of a line so it no longer runs:
let name = "Ravi"
// print("Debug: name is \(name)")
print("Hello, \(name)!")Hello, Ravi!
Tip: In Xcode, select some lines and press ⌘ / to comment or uncomment them all at once.
Documentation comments
Comments that start with /// (or /** … */) are documentation comments. Xcode shows them in Quick Help when you Option-click a name, and tools like DocC turn them into web documentation. They use Markdown:
/// Returns the area of a rectangle.
///
/// - Parameters:
/// - width: The width in centimetres.
/// - height: The height in centimetres.
/// - Returns: The area in square centimetres.
func area(width: Double, height: Double) -> Double {
width * height
}| Syntax | Kind | Typical use |
|---|---|---|
// text |
single-line | short explanations, disabling one line |
/* text */ |
multi-line (nestable) | longer notes, disabling a block |
/// text |
documentation | describing functions and types for Quick Help |
// MARK: - Title |
marker | creates a section heading in Xcode's jump bar |
// TODO: / // FIXME: |
marker | reminders that Xcode lists in the jump bar |
Writing good comments
- Explain why, not what.
count += 1 // add one to countadds nothing;// the header row is not a recorddoes. - Keep comments up to date — a wrong comment is worse than none.
- Prefer clear names over comments:
let secondsPerDay = 86_400needs no explanation.
Test yourself
Which of these is a single-line comment in Swift?
- # note
- -- note
- // note
- <!-- note -->
What is special about Swift's /* */ comments compared with C?
- They can only span one line
- They can be nested
- They are printed at runtime
- They must start with
///
What does a /// comment create?
- A compiler warning
- Documentation shown in Xcode Quick Help
- A TODO marker
- A nested comment