Chapter 8: Swift Comments
1. Why do we write comments at all?
Comments are notes for humans — the compiler completely ignores them.
Main reasons people write comments:
- Explain why something is done (not just what)
- Document public API so others (or future you) understand how to use it
- Temporarily disable code during debugging
- Add legal notices / license / copyright
- Mark sections in long files
- Leave TODOs, FIXMEs, warnings
2. The two main types of comments in Swift
Type A: Single-line comment — //
Most common style — used everywhere.
|
0 1 2 3 4 5 6 7 8 9 10 11 |
// This is a single-line comment let name = "Priya" // inline comment after code // You can write as many lines as you want // each starting with // |
Very common patterns:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } // Configuration private func setupUI() { // Colors backgroundColor = .systemBackground // Fonts titleLabel.font = .preferredFont(forTextStyle: .headline) // Layout constraints NSLayoutConstraint.activate([ // ... ]) } // TODO: Handle offline mode later // FIXME: This calculation is wrong on leap years // WARNING: Do not call this on main thread! |
Type B: Multi-line comment — /* … */
Used less often, but still important in specific cases.
|
0 1 2 3 4 5 6 7 8 9 10 |
/* This is a multi-line comment. It can span several lines. Very useful for longer explanations. */ |
Realistic examples where people actually use /* */:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/* JSON response structure from API: { "user": { "id": 1234, "name": "Aarav", "email": "aarav@example.com" }, "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } */ |
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
/* ╔════════════════════════════════════════════╗ ║ IMPORTANT NOTICE ║ ║ ║ ║ Never commit real API keys to git! ║ ║ Use environment variables or Secrets. ║ ╚════════════════════════════════════════════╝ */ |
3. Special comment styles that modern Swift developers love
3.1 // MARK: – Section headers (very very common in Xcode)
Xcode shows these in the jump bar (the dropdown above the editor).
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// MARK: - Properties private let apiClient = APIClient() private var userSession: UserSession? // MARK: - Public Methods func login(email: String, password: String) async throws { // ... } // MARK: - Private Helpers private func validateInput() -> Bool { // ... } |
You can also add a separator line:
|
0 1 2 3 4 5 6 |
// MARK: - View Life Cycle ----------------------------------- |
3.2 Documentation comments — /// (super important!)
These generate beautiful documentation when you Option-click a symbol in Xcode.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/// Calculates the total price including tax. /// /// - Parameters: /// - subtotal: The price before tax (must be positive) /// - taxRate: Tax rate as a percentage (0...100) /// - Returns: The final amount to pay /// - Throws: `PricingError.negativeSubtotal` if subtotal is negative func calculateTotal(subtotal: Double, taxRate: Double) throws -> Double { guard subtotal >= 0 else { throw PricingError.negativeSubtotal } let tax = subtotal * (taxRate / 100) return subtotal + tax } |
When someone Option-clicks this function in Xcode, they see:
- Summary
- Parameters table
- Returns
- Throws
Very professional — almost every public function in good libraries uses ///.
3.3 /** … */ — old-style doc comments (still works, less common now)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/** Calculates the area of a circle. - parameter radius: The radius of the circle - returns: Area in square units */ func circleArea(radius: Double) -> Double { return .pi * radius * radius } |
Most people now prefer /// because it’s cleaner.
4. Good habits & bad habits (real developer advice)
Good habits:
- Explain WHY, not just WHAT Bad: // add 1 to counter Good: // increment retry counter after failed network attempt
- Keep comments up to date — delete or fix outdated ones
- Use // MARK: to organize long files
- Use /// for public functions, types, properties
- Use // TODO: / // FIXME: / // NOTE: consistently
Bad habits (please avoid):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
// bad: useless comment let x = 10 // set x to 10 // bad: comment that just repeats the code user.age = user.age + 1 // increase age by 1 // bad: lying comment (very dangerous!) let isAdmin = true // only for testing |
5. Quick reference table – when to use each style
| Style | Syntax | Best used for | Frequency in modern code |
|---|---|---|---|
| // | Single line | inline notes, temporary disable, TODO/FIXME | ★★★★★ (most common) |
| // MARK: | Section header | organizing code in files (shows in Xcode jump bar) | ★★★★★ |
| /// | Documentation | public API, functions, structs, properties | ★★★★ (very important) |
| /* … */ | Multi-line block | long explanations, ASCII art notices, JSON examples | ★★ (occasional) |
| /** … */ | Old doc block | legacy code or some open-source projects | ★ (rare now) |
6. Small realistic examples you can copy-paste
Example 1 – Clean function documentation
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
/// Formats a phone number into international style. /// /// Example: "9876543210" → "+91 98765 43210" /// /// - Parameter rawNumber: Raw Indian phone number (10 digits) /// - Returns: Formatted string or nil if invalid func formatIndianPhoneNumber(_ rawNumber: String) -> String? { // Remove all non-digits let digits = rawNumber.filter { $0.isNumber } // Check length guard digits.count == 10 else { return nil } // Format: +91 XXXXX XXXXX let prefix = "+91 " let part1 = String(digits.prefix(5)) let part2 = String(digits.dropFirst(5)) return prefix + part1 + " " + part2 } |
Example 2 – Organized struct
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// MARK: - Models struct UserProfile { // MARK: - Properties let id: UUID var name: String var email: String? // MARK: - Computed Properties var displayName: String { name.trimmingCharacters(in: .whitespacesAndNewlines) } // MARK: - Initialization init(id: UUID = UUID(), name: String, email: String? = nil) { self.id = id self.name = name self.email = email } } |
Would you like to continue with:
- Writing good documentation comments in more detail
- Using TODO / FIXME / MARK effectively
- Comment styles in SwiftUI vs UIKit vs server-side Swift
- How to generate documentation from comments (DocC)
- Or move to another topic (variables, functions, printing, etc.)
Just tell me what you’d like next — we’ll keep the same detailed, teacher-like style 😊
