Comments in Swift
Single-Line Comments
A single-line comment starts with // and continues to the end of that line. The compiler ignores everything after // on that line entirely.
Example: Single-Line Comments
// This prints a greeting
print("Hello, Swift!") // this part is also a comment
Login to try C/C++/Java/PHP code in the editor
Multi-Line Block Comments
A block comment starts with /* and ends with */, and can span multiple lines, making it useful for longer explanations.
Example: Multi-Line Block Comments
/*
This program demonstrates
multi-line block comments
*/
print("Block comments explained")
Login to try C/C++/Java/PHP code in the editor
Nested Block Comments
Unlike C or Java, Swift allows block comments to be nested inside one another, which makes it easy to comment out a section of code that already contains a block comment.
Note: This is handy for temporarily disabling a chunk of code that already has comments inside it.
Example: Nested Block Comments
/* outer comment /* nested inner comment */ still outer */
print("Swift supports nested block comments")
Login to try C/C++/Java/PHP code in the editor
- Believing comments affect how the program runs; the compiler skips them entirely.
- Using comments to explain obvious code instead of explaining *why* a non-obvious decision was made.
- Forgetting that block comments
/* */can be nested in Swift, unlike in many other C-family languages, which can cause confusion when mixing styles.
//starts a single-line comment that runs to the end of the line./* ... */marks a multi-line block comment.- Swift uniquely allows nested block comments (
/* /* ... */ */). - Good comments explain *why* code does something, not just *what* it does.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: