0
0
Swiftprogramming~15 mins

Comments and documentation markup in Swift - Deep Dive

Choose your learning style9 modes available
Overview - Comments and documentation markup
What is it?
Comments are notes in code that explain what the code does, but they do not run when the program runs. Documentation markup is a special way to write comments so tools can create helpful guides automatically. In Swift, comments help programmers understand code better and keep it organized. They can be simple notes or detailed explanations that describe how parts of the code work.
Why it matters
Without comments and documentation, code can be confusing and hard to fix or improve, especially when many people work on it or when you return to it after a long time. Good comments save time and prevent mistakes by making the code's purpose clear. Documentation markup helps create easy-to-read manuals that explain how to use code parts, making teamwork and learning faster and smoother.
Where it fits
Before learning comments, you should know basic Swift syntax and how to write simple programs. After mastering comments and documentation markup, you can learn about code organization, testing, and creating libraries or frameworks that others can use.
Mental Model
Core Idea
Comments and documentation markup are like labels and instruction manuals inside your code that explain what it does without changing how it works.
Think of it like...
Imagine building a LEGO set: comments are the sticky notes you put on pieces to remind yourself what they do, and documentation markup is the instruction booklet that helps others build the same set correctly.
Code with comments and documentation markup:

┌─────────────────────────────┐
│ // This function adds two numbers  │  ← Simple comment
│ func add(a: Int, b: Int) -> Int { │
│     return a + b                  │
│ }                              │
│ /**                           │
│  Adds two integers and returns │
│  the result.                  │
│  - Parameters:                │
│    - a: First number          │
│    - b: Second number         │
│  - Returns: Sum of a and b    │
│ */                            │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationBasic single-line comments
🤔
Concept: Learn how to write simple notes in code using single-line comments.
In Swift, you can write a single-line comment by starting the line with two slashes `//`. Everything after `//` on that line is ignored by the computer and is only for humans reading the code. Example: // This is a comment explaining the next line let number = 5 The computer runs `let number = 5` but ignores the comment.
Result
The program runs normally, but the comment helps anyone reading the code understand what `number` means.
Understanding single-line comments is the first step to making your code clearer and easier to follow.
2
FoundationMulti-line comments for longer notes
🤔
Concept: Use multi-line comments to write explanations that span several lines.
Sometimes you need more space to explain something. Swift lets you write multi-line comments by starting with `/*` and ending with `*/`. Everything between these marks is ignored by the computer. Example: /* This is a multi-line comment. It can explain complex ideas or temporarily disable code. */ let x = 10 You can also nest multi-line comments inside each other.
Result
You can write detailed notes or disable blocks of code without deleting them.
Knowing multi-line comments helps you document complex parts or test code safely by hiding it temporarily.
3
IntermediateDocumentation comments with markup
🤔Before reading on: do you think documentation comments are just longer comments or do they have a special format? Commit to your answer.
Concept: Swift uses special comment styles to create documentation that tools can read and turn into guides.
Documentation comments start with `///` for single lines or `/** ... */` for blocks. They support special markup tags like `- Parameters:` and `- Returns:` to describe functions clearly. Example: /// Adds two numbers and returns the result. /// - Parameters: /// - a: First number /// - b: Second number /// - Returns: The sum of a and b func add(a: Int, b: Int) -> Int { return a + b } Tools like Xcode use these comments to show helpful hints and generate documentation pages.
Result
Your code becomes self-explanatory and tools can create user-friendly manuals automatically.
Understanding documentation markup unlocks powerful ways to communicate your code's purpose to others and to yourself.
4
IntermediateUsing comments to explain intent, not code
🤔Before reading on: do you think comments should explain what the code does line-by-line or why it does it? Commit to your answer.
Concept: Good comments focus on why the code exists or what problem it solves, not just what each line does.
Instead of repeating the code, comments should explain the reason behind it. Example: // Calculate the total price including tax let totalPrice = price * 1.08 This comment tells why we multiply by 1.08, which is more helpful than just saying 'multiply price'. Avoid comments like: // Add 1 to x x = x + 1 because the code already says that clearly.
Result
Comments become meaningful guides that help others understand your thinking and decisions.
Knowing what to comment prevents clutter and makes your notes truly valuable.
5
IntermediateCommenting out code safely
🤔Before reading on: do you think commenting out code is a good way to delete it permanently? Commit to your answer.
Concept: Comments can temporarily disable code without deleting it, useful for testing or debugging.
If you want to stop a piece of code from running but keep it for later, you can comment it out. Example: // let oldValue = calculateOldValue() This line won't run but stays in the file. Use multi-line comments to disable bigger blocks: /* func oldFunction() { // old code } */ Remember to remove unused code eventually to keep your project clean.
Result
You can test changes safely without losing previous code.
Understanding this helps avoid accidental permanent deletions and supports safer experimentation.
6
AdvancedGenerating documentation with Swift tools
🤔Before reading on: do you think documentation comments automatically create manuals or do you need extra steps? Commit to your answer.
Concept: Swift tools can read documentation markup and generate formatted documents or show inline help in editors.
Xcode and other tools parse documentation comments to provide quick help when you use functions or classes. You can also generate full HTML or other formats using tools like Jazzy. Example: /// Adds two numbers. /// - Parameters: /// - a: First number /// - b: Second number /// - Returns: Sum of a and b func add(a: Int, b: Int) -> Int { return a + b } Running documentation tools creates user-friendly guides from these comments.
Result
Your codebase gains professional-quality documentation that helps users and developers.
Knowing how to generate docs turns comments from simple notes into powerful communication tools.
7
ExpertAdvanced markup and customization tricks
🤔Before reading on: do you think documentation markup supports custom tags or rich formatting? Commit to your answer.
Concept: Swift documentation markup supports advanced features like code blocks, lists, and custom tags to create rich, readable docs.
You can add code examples inside comments using triple backticks: /// Example usage: /// ```swift /// let result = add(a: 2, b: 3) /// print(result) // 5 /// ``` You can also use lists and emphasize text: /// - Important: /// Use this function only with positive numbers. Custom tags and formatting help create clear, professional documentation. Some tools allow you to extend markup with your own tags for special needs.
Result
Your documentation looks polished and can teach users effectively with examples and warnings.
Mastering advanced markup elevates your documentation from basic notes to comprehensive guides that reduce support and errors.
Under the Hood
When Swift code runs, the compiler ignores comments completely—they do not affect the program's behavior or performance. Documentation comments are specially recognized by tools like Xcode's source editor and external documentation generators. These tools parse the markup syntax inside comments to create structured help content, tooltips, and formatted manuals. This separation keeps code clean and fast while enabling rich explanations outside the executable code.
Why designed this way?
Comments were designed to be ignored by the compiler to avoid slowing down programs or causing errors. Documentation markup evolved to standardize how explanations are written so tools can automate help generation, improving developer productivity. This design balances code clarity, performance, and maintainability. Alternatives like embedding documentation in separate files were less convenient and prone to getting out of sync with code.
┌───────────────┐
│ Swift Source  │
│ Code + Comments│
└──────┬────────┘
       │ Compiler ignores comments
       ▼
┌───────────────┐
│ Executable    │
│ Code Only     │
└───────────────┘

Documentation Tools
┌───────────────┐
│ Parse comments│
│ with markup   │
└──────┬────────┘
       ▼
┌───────────────┐
│ Generate docs │
│ (HTML, tooltips)│
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do comments slow down your Swift program when it runs? Commit to yes or no.
Common Belief:Comments make the program slower because they add extra text.
Tap to reveal reality
Reality:Comments are completely ignored by the Swift compiler and do not affect the program's speed or size.
Why it matters:Believing this might make learners avoid writing helpful comments, making code harder to understand and maintain.
Quick: Should you write comments that just repeat what the code says? Commit to yes or no.
Common Belief:Good comments explain exactly what each line of code does, even if obvious.
Tap to reveal reality
Reality:Effective comments explain why the code exists or what it intends, not just what it does line-by-line.
Why it matters:Repeating code wastes time and clutters files, making it harder to find useful explanations.
Quick: Do documentation comments automatically create manuals without extra tools? Commit to yes or no.
Common Belief:Writing documentation comments alone is enough to produce user manuals.
Tap to reveal reality
Reality:Documentation comments need tools like Xcode or Jazzy to generate readable manuals or help pop-ups.
Why it matters:Expecting automatic manuals without tools can lead to confusion and missed opportunities to create helpful docs.
Quick: Can you nest multi-line comments inside each other in Swift? Commit to yes or no.
Common Belief:Multi-line comments cannot be nested; doing so causes errors.
Tap to reveal reality
Reality:Swift supports nesting multi-line comments, allowing you to comment out blocks that already contain comments.
Why it matters:Knowing this prevents frustration when trying to disable code blocks that include comments.
Expert Zone
1
Documentation comments can include rich formatting like code blocks and lists, which many developers overlook, missing chances to create clearer docs.
2
Nested multi-line comments allow safe temporary disabling of complex code sections, a feature not common in all languages.
3
Xcode's quick help feature uses documentation markup to show inline hints, but the quality depends on how well you write your comments.
When NOT to use
Avoid over-commenting trivial code or writing comments that duplicate code logic. Instead, refactor code to be self-explanatory. For large projects, use external documentation tools and keep comments focused on intent and usage rather than implementation details.
Production Patterns
In professional Swift projects, developers use documentation markup extensively to generate API references and quick help. Comments are used to explain complex algorithms, assumptions, and usage constraints. Teams often enforce comment quality through code reviews and automated tools that check for missing documentation.
Connections
Code readability
Comments and documentation markup directly improve code readability.
Understanding how to write effective comments helps make code easier to read and maintain, which is the core goal of readable code.
Technical writing
Documentation markup is a form of technical writing embedded in code.
Learning documentation markup improves your technical writing skills, enabling you to communicate complex ideas clearly and precisely.
User manuals in product design
Documentation markup creates manuals similar to user guides in product design.
Knowing how to write clear documentation in code parallels creating helpful user manuals, emphasizing clarity and user understanding across fields.
Common Pitfalls
#1Writing comments that just repeat the code.
Wrong approach:// Increment x by 1 x = x + 1
Correct approach:// Increase x to track the number of attempts x = x + 1
Root cause:Misunderstanding that comments should explain why, not what, leads to redundant and unhelpful notes.
#2Leaving outdated comments after code changes.
Wrong approach:// This function multiplies by 2 func double(x: Int) -> Int { return x * 3 }
Correct approach:// This function multiplies by 3 func double(x: Int) -> Int { return x * 3 }
Root cause:Failing to update comments when code changes causes confusion and mistrust in documentation.
#3Using comments to disable large code blocks without nesting support.
Wrong approach:/* func test() { /* inner comment */ } */
Correct approach:/* func test() { /* inner comment */ } */ // Swift supports nested comments, so this works correctly
Root cause:Not knowing Swift supports nested comments leads to errors or frustration when commenting out code.
Key Takeaways
Comments are notes in code that help humans understand what the code does without affecting how it runs.
Documentation markup uses special comment styles to create structured explanations that tools can turn into manuals and inline help.
Good comments explain why code exists or what it intends, not just what each line does.
Swift supports both single-line and nested multi-line comments, giving flexibility in writing notes or disabling code.
Using documentation comments well improves teamwork, learning, and maintenance by making code self-explanatory and professionally documented.