Swift Comments and Documentation Comments (///) Explained

Swift comments help you explain code to human readers without changing how the program runs. Documentation comments go a step further: they are designed to describe declarations such as functions, types, and properties so tools like Xcode can show helpful Quick Help information. In this article, you will learn the difference between regular comments and documentation comments in Swift, how to write them correctly, when to use each one, and how to avoid common mistakes.

Quick answer: In Swift, use // for a single-line comment, /* ... */ for a block comment, and /// for a documentation comment that describes the declaration that follows. Regular comments are for code notes, while /// comments are for API-style documentation shown in Xcode Quick Help.

Difficulty: Beginner

Helpful to know first: You will understand this better if you already know basic Swift syntax, how functions and variables are declared, and how code is organized into types such as structs and classes.

1. What Is Swift Comments & Documentation Comments (///)?

Comments are non-executed text written inside source code to explain intent, clarify logic, or temporarily disable code while testing. Swift documentation comments are a special kind of comment used to document declarations in a structured, tool-friendly way.

Swift also supports nested block comments, which is useful when commenting out a block of code that already contains block comments. That behavior is different from some other languages and can be surprisingly helpful during debugging.

One important comparison is regular comments versus documentation comments:

2. Why Swift Comments & Documentation Comments (///) Matters

Good comments make code easier to understand, maintain, review, and reuse. This matters even in small Swift programs, but it becomes especially important in larger projects, team environments, shared libraries, and teaching code to new developers.

Comments matter because they help you:

Comments do not replace clear naming or good code structure. If a variable or function needs a paragraph of explanation just to be understood, the code may need better names or a simpler design. Use comments to add meaning, not to excuse unclear code.

3. Basic Syntax or Core Idea

Swift has three comment forms you will use most often. The syntax is simple, but the purpose of each form is slightly different.

Single-line comments with //

Use a single-line comment for short notes above code or at the end of a line.

// Store the user's display name
let displayName = "Taylor"

let maxScore = 100 // maximum allowed score

This is the most common comment style for short explanations and local notes.

Block comments with /* ... */

Use a block comment for longer explanations or when commenting out multiple lines at once.

/*
 This function formats a title for display.
 It trims spaces and capitalizes each word.
*/
func formatTitle(_ title: String) -> String {
    title.trimmingCharacters(in: .whitespacesAndNewlines).capitalized
}

Block comments are useful for multi-line explanations, but many teams still prefer line comments for readability and easier editing.

Documentation comments with ///

Use a documentation comment immediately above a declaration you want to document for users of that code.

/// Returns a greeting for the provided name.
func greet(name: String) -> String {
    "Hello, \(name)!"
}

This comment is attached to the function declaration below it. In Xcode, that information can appear in Quick Help and symbol documentation.

Structured documentation fields

Swift documentation comments also support common documentation markers such as parameters and return values.

/// Calculates the area of a rectangle.
/// - Parameters:
///   - width: The rectangle width.
///   - height: The rectangle height.
/// - Returns: The area as a Double.
func rectangleArea(width: Double, height: Double) -> Double {
    width * height
}

This format makes your documentation more useful because it explains inputs and outputs clearly.

4. Step-by-Step Examples

Example 1: Adding a simple note above a variable

Here, a regular single-line comment explains the purpose of a value.

// The app's default timeout in seconds
let defaultTimeout = 30

This works well because the comment adds context that the number alone does not fully provide.

Example 2: Using a block comment for a longer explanation

This example shows a multi-line block comment describing a rule in the code.

/*
 We accept usernames that are between 3 and 12 characters.
 Spaces are not allowed.
 This rule matches the validation used on the server.
*/
func isValidUsername(_ username: String) -> Bool {
    username.count >= 3 && username.count <= 12 && !username.contains(" ")
}

This kind of comment is helpful when a business rule needs a little more explanation.

Example 3: Documenting a function with ///

Now the comment is aimed at someone using the function, not just reading its implementation.

/// Converts a temperature from Celsius to Fahrenheit.
/// - Parameter celsius: The temperature in degrees Celsius.
/// - Returns: The temperature in degrees Fahrenheit.
func fahrenheit(from celsius: Double) -> Double {
    (celsius * 9 / 5) + 32
}

This is the right approach for reusable code because it explains what the function expects and what it returns.

Example 4: Documenting a type and its property

Documentation comments can be added to types and members, not just functions.

/// Represents a book in a reading list.
struct Book {
    /// The book title shown to the user.
    let title: String
    
    /// The name of the author.
    let author: String
}

This makes the model easier to understand in a shared codebase or package.

Example 5: Nested block comments

Swift supports nested block comments, which is useful when temporarily disabling code that already contains comments.

/*
// Old test value
let sampleName = "Preview"

/* This block is also safely nested. */
*/

Not every language allows this, but Swift does. That makes large temporary comment blocks safer to use during development.

5. Practical Use Cases

6. Common Mistakes

Mistake 1: Using regular comments when API documentation is needed

Beginners often write a normal // comment above a function and expect it to behave like documentation.

Problem: A regular comment does not provide structured API documentation in the same way as a documentation comment, so Quick Help and generated docs may not show what you expect.

// Returns the full name for display.
func fullName(first: String, last: String) -> String {
    "\(first) \(last)"
}

Fix: Use /// when the comment is meant to document the declaration for other developers and tools.

/// Returns the full name for display.
/// - Parameters:
///   - first: The person's first name.
///   - last: The person's last name.
/// - Returns: A combined display name.
func fullName(first: String, last: String) -> String {
    "\(first) \(last)"
}

The corrected version works because the declaration now has proper documentation metadata attached to it.

Mistake 2: Writing documentation comments too far away from the declaration

A documentation comment must describe the declaration directly below it. If other code appears between them, the documentation may not attach to the symbol you intended.

Problem: This comment is separated from the function by another declaration, so the documentation no longer clearly belongs to the target function.

/// Formats a price as text.
let currencySymbol = "$"

func formattedPrice(_ amount: Double) -> String {
    "\(currencySymbol)\(amount)"
}

Fix: Place the documentation comment immediately above the declaration it documents.

let currencySymbol = "$"

/// Formats a price as text.
/// - Parameter amount: The numeric price value.
/// - Returns: A currency string for display.
func formattedPrice(_ amount: Double) -> String {
    "\(currencySymbol)\(amount)"
}

The corrected version works because the comment is now clearly attached to the function declaration.

Mistake 3: Commenting what the code obviously says

Comments should add value. Repeating the code in words makes files longer without improving understanding.

Problem: This comment adds no useful context because anyone reading the code can already see exactly what it does.

// Add 1 to count
count += 1

Fix: Either remove the comment or explain the reason behind the operation if it is not obvious.

// Count the current user before checking the team limit.
count += 1

The corrected version works because it explains the purpose of the increment instead of restating the syntax.

Mistake 4: Letting comments become outdated

A stale comment is often worse than no comment because it actively misleads readers.

Problem: The comment says one thing, but the code does something else, which creates confusion and bugs during maintenance.

// Maximum of 10 items allowed
let maxItems = 20

Fix: Update the comment immediately when the code changes, or remove the comment if the code is already clear.

// Maximum of 20 items allowed
let maxItems = 20

The corrected version works because the explanation now matches the actual behavior of the code.

7. Best Practices

Practice 1: Comment the reason, not the obvious action

The best comments explain intent, constraints, and decisions. They should answer questions like “Why is this here?” or “What rule is this enforcing?”

// Less helpful
index += 1

// Better: skip the header row before processing data rows
index += 1

This is better because the second comment gives business or structural context, not just a literal translation of the code.

Practice 2: Use /// for reusable declarations

If other developers are likely to call a function or use a type, documentation comments make that code easier to discover and use correctly.

/// Checks whether the password meets the minimum rules.
/// - Parameter password: The password to validate.
/// - Returns: True when the password is at least 8 characters long.
func isValidPassword(_ password: String) -> Bool {
    password.count >= 8
}

This practice improves editor help and makes the API easier to understand without opening the implementation.

Practice 3: Keep comments close to the code they describe

Readers should never have to guess which line or declaration a comment belongs to.

/// The number of login attempts before temporary lockout.
let maxLoginAttempts = 5

Placing the comment directly above the declaration keeps the meaning clear and avoids accidental mismatch.

Practice 4: Prefer clear code before adding extra comments

If a better name can remove the need for a comment, that is usually the stronger solution.

// Less clear name needs explanation
let x = 60

// Better naming reduces comment pressure
let sessionTimeoutSeconds = 60

The second version is easier to understand immediately, even without an extra note.

8. Limitations and Edge Cases

A common “not working” situation is expecting Xcode Quick Help to show detailed docs for a function that only has regular comments. In that case, switch to /// and place the documentation directly above the declaration.

9. Practical Mini Project

This small example shows how regular comments and documentation comments can work together in a realistic Swift file. The regular comments explain implementation intent, while the documentation comments describe the public interface of reusable code.

/// A simple task item in a to-do list.
struct Task {
    /// The task title shown in the list.
    let title: String
    
    /// Whether the task has been completed.
    var isDone: Bool
}

/// Returns the number of completed tasks.
/// - Parameter tasks: The list of tasks to inspect.
/// - Returns: The count of tasks whose isDone value is true.
func completedTaskCount(in tasks: [Task]) -> Int {
    // Count only the finished tasks for summary output.
    tasks.filter { $0.isDone }.count
}

/// Builds a short status message for the current task list.
/// - Parameter tasks: The tasks to summarize.
/// - Returns: A human-readable summary string.
func taskSummary(for tasks: [Task]) -> String {
    let finishedCount = completedTaskCount(in: tasks)
    let totalCount = tasks.count
    
    "Completed \(finishedCount) of \(totalCount) tasks."
}

let tasks = [
    Task(title: "Write outline", isDone: true),
    Task(title: "Review examples", isDone: false),
    Task(title: "Publish article", isDone: true)
]

print(taskSummary(for: tasks))

This mini project demonstrates a good balance: the API-facing parts use ///, while the internal implementation uses a normal comment for a local note.

10. Key Points

11. Practice Exercise

Try this exercise to practice both regular comments and documentation comments.

Expected output: After depositing 50.0 into an account starting at 100.0, printing the result should show 150.0.

Hint: Use var for the balance if it needs to change, and place each /// comment directly above the declaration it documents.

/// Represents a simple bank account with a current balance.
struct BankAccount {
    var balance: Double
    
    /// Adds money to the account balance.
    /// - Parameter amount: The amount to deposit.
    /// - Returns: The updated account balance.
    mutating func deposit(_ amount: Double) -> Double {
        // Increase the stored balance before returning it.
        balance += amount
        return balance
    }
}

var account = BankAccount(balance: 100.0)
let newBalance = account.deposit(50.0)
print(newBalance)

12. Final Summary

Swift comments are simple to write, but using them well takes judgment. Regular comments with // and /* ... */ are best for implementation notes, reasoning, and temporary explanations inside a file. Documentation comments with /// are different: they are meant to describe declarations in a way that helps other developers understand and use your code.

As a rule, use comments to explain intent, decisions, constraints, and behavior that are not obvious from the code itself. For reusable Swift code, prefer documentation comments so Xcode Quick Help can surface helpful details like parameters and return values. If you combine clear naming, well-structured code, and accurate comments, your Swift files become much easier to maintain and reuse.

A strong next step is to learn how to write clear Swift functions and parameter labels, because documentation comments become much more useful when the declarations they describe are already well designed.