Skip to Content
Course content

50: Documentation Comments and DocC

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you've just bought a complex piece of flat-pack furniture. You open the box and find a set of instructions. Now, some instructions are useless—they just say "Put the screw in the hole," which is obvious because that's the only place the screw fits. But great instructions tell you why you're using a specific bolt, warn you not to over-tighten a certain joint, and show you a diagram of what the final piece should look like. If those instructions were missing, you'd spend three hours guessing, probably put a shelf in backward, and end up frustrated.

In Swift, documentation comments are those high-quality instructions. While standard comments (//) are like scribbles in the margin for yourself, documentation comments (///) are the official manual for anyone else (including future you) who uses your code. DocC is the tool that takes those manuals and automatically turns them into a polished, searchable website, similar to Apple's own developer documentation.

The Power of the Triple Slash

The first thing you need to know is the difference between a comment and a documentation comment. A standard // comment is ignored by the compiler and stays hidden in the source code. But when you use three slashes—///—you're telling Xcode: "This is important. This describes how the code works."

The immediate magic happens when you Option-Click a function name in Xcode. If you used //, you see nothing. If you used ///, Xcode pops up a "Quick Help" window. I can't stress enough how much this saves time. You don't have to jump to the definition of a function to remember what it does; the answer just floats right there in your face.

Structuring the Manual

You can't just write a paragraph and hope for the best. DocC looks for specific keywords to organize the information. I usually follow a specific pattern: a one-line summary, a deeper discussion, and then the technical details.

/// Calculates the total price including tax.
///
/// This method takes the base price and applies the regional tax rate.
/// It rounds the result to two decimal places to ensure currency accuracy.
///
/// - Parameter price: The initial cost of the item before taxes.
/// - Parameter taxRate: The tax percentage as a decimal (e.g., 0.07 for 7%).
/// - Returns: The final price as a formatted Double.
func calculateTotal(price: Double, taxRate: Double) -> Double {
    return (price * (1 + taxRate)).rounded()
}

Notice the - Parameter: and - Returns: lines. These aren't just for show; DocC parses these specifically to create those neat tables you see in professional API docs. If your function can throw an error, you'd add a - Throws: section to warn the caller about what might go wrong.

Adding Flavor with Markdown

Since DocC uses Markdown, you aren't limited to plain text. I often use backticks to reference other types or variables. If I write Use the `TaxCalculator` class to handle this, DocC actually turns that into a clickable link to the TaxCalculator documentation. You can also use bold text, italics, and even code blocks to provide examples of how to call your function. It transforms your code from a "black box" into a guided experience.

Turning Comments into a Website

Now, the "DocC" part. Beyond the Quick Help pop-ups, Xcode can compile all these /// comments into a full-blown documentation archive. You go to Product > Build Documentation, and Xcode generates a local website.

This is a game-changer when you're working on a team. Instead of spending your afternoon in a Zoom call explaining how your new networking layer works, you just send your teammate the documentation link. It's a professional touch that separates "someone who can code" from a "software engineer."




📋 Practical Task

Documenting a Payment Processing Engine

You have been handed a PaymentProcessor class that was written by a developer who left the company without leaving a single note. The code works, but no one knows how to use it safely. Your task is to add professional documentation comments to this class so that it can be rendered by DocC.

Requirements:

  • Add a high-level summary and discussion for the PaymentProcessor class.
  • Document the processPayment method using the - Parameter:, - Returns:, and - Throws: keywords.
  • Use Markdown backticks to reference the PaymentError enum within your descriptions.
  • Ensure the validateCard method has a clear summary explaining what it checks for.
enum PaymentError: Error {
    case insufficientFunds
    case expiredCard
    case invalidCVV
}

class PaymentProcessor {
    func validateCard(_ cardNumber: String) -> Bool {
        // Imagine complex validation logic here
        return cardNumber.count == 16
    }

    func processPayment(amount: Double, cardNumber: String) throws -> String {
        guard validateCard(cardNumber) else: {
            throw PaymentError.expiredCard 
        }
        
        if amount > 10000 {
            throw PaymentError.insufficientFunds
        }
        
        return "TXN_\(Int.random(in: 1000...9999))"
    }
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.