Comments (// and /* */)
Swift has four types of comments: single-line comments (//), block comments (/* */), line documentation comments (///), and block documentation comments (/** */). Documentation comments support Markdown syntax and are displayed in Xcode's Quick Help panel (Option+click). Apple's Swift-DocC tool can also generate full HTML documentation from them.
Syntax
// Single-line comment — everything from // to the end of the line is a comment.
let x = 10 // Inline comment — can also be written after code.
/* Block comment — everything between /* and */ is a comment.
Swift block comments can be nested. */
/* outer /* inner */ outer continues — this is valid in Swift */
/// Line doc comment — documents the declaration immediately following it
/// (function, class, struct, etc.). Supports Markdown syntax.
/// Displayed in Xcode's Quick Help panel.
func exampleFunction() {}
/** Block doc comment — same role as ///.
* Useful for writing multi-line documentation in a single block.
* Displayed in Xcode's Quick Help panel.
*/
func blockDocFunction() {}
Comment Types
| Type | Syntax | Description |
|---|---|---|
| Single-line comment | // text | Everything from // to the end of the line becomes a comment. The most frequently used comment type. |
| Block comment | /* text */ | Used when writing a comment that spans multiple lines. Block comments can be nested in Swift. |
| Line doc comment | /// text | Documents the declaration immediately following it. Supports Markdown syntax and is shown in Xcode Quick Help. |
| Block doc comment | /** text */ | The block version of ///. Allows writing multi-line documentation in a single block. |
Documentation Comment Markdown and Keywords
Swift documentation comments support standard Markdown syntax. Specific keywords such as - Parameter are interpreted by Xcode and rendered in dedicated sections of the Quick Help panel.
| Keyword | Description |
|---|---|
| - Parameter name: description | Documents a function parameter. Write one line per parameter. |
| - Parameters: / - name: description | An alternative grouped form for documenting multiple parameters. |
| - Returns: description | Documents the return type and its meaning. |
| - Throws: description | Documents errors that may be thrown. |
| - Note: text | Adds supplementary information. |
| - Warning: text | Adds a warning. Displayed with emphasis in Xcode. |
| - Important: text | Highlights critical information. |
| - Example: text | Provides a usage example. |
| - SeeAlso: reference | Points to related declarations or external resources. |
When to Write Comments and When Not To
| Decision | Situation | Reason |
|---|---|---|
| Write a comment | The reason why something was implemented a certain way | Design decisions and trade-offs that cannot be understood from the code alone help your future self and other developers. |
| Write a comment | Complex algorithms or formulas | Add a brief description of what a piece of logic does when its behavior is not immediately obvious at a glance. |
| Write a comment | Public API (functions, classes, structs, protocols) | Adding /// doc comments makes them appear in Xcode Quick Help and in Swift-DocC generated HTML documentation. |
| Write a comment | Temporarily disabled code during debugging | Leaving a note explaining why code was commented out and when it can be removed reduces the risk of forgetting to clean it up later. |
| No comment needed | Logic that is obvious from reading the code | Self-evident explanations become noise. Clear variable and function names remove the need for such comments. |
| No comment needed | Change history or deleted code | Because version control (git) is available, there is no need to keep old code or change dates in comments. |
Sample Code
comment_basic.swift
// comment_basic.swift — Basic usage of Swift comment syntax.
let items = ["widget", "gadget", "device"]
let prices = [1200, 3500, 800] // Prices before tax
/* Calculate the total and print the result */
let total = prices.reduce(0, +)
for (item, price) in zip(items, prices) {
print(String(format: "%-10@ %5d yen", item, price))
}
print("----------")
print(String(format: "%-10@ %5d yen", "Total", total))
Running the above produces the following output:
$ swift comment_basic.swift widget 1200 yen gadget 3500 yen device 800 yen ---------- Total 5500 yen
comment_doc.swift
// comment_doc.swift — Documenting functions with doc comments.
// Option+click in Xcode to see the Quick Help panel.
/// Computes the average of an integer array and returns it.
///
/// Returns `nil` if the array is empty (does not crash).
///
/// - Parameter values: An array of integers to average
/// - Returns: The average as a `Double`, or `nil` if the array is empty.
///
/// ## Example
///
/// ```swift
/// let avg = calculateAverage([85, 92, 78, 95, 60])
/// print(avg!) // 82.0
/// ```
func calculateAverage(_ values: [Int]) -> Double? {
guard !values.isEmpty else {
// Empty array cannot be averaged — return nil
return nil
}
let sum = values.reduce(0, +)
/* Cast to Double to avoid integer division */
return Double(sum) / Double(values.count)
}
/** Block doc comment — another way to write the same documentation.
* The content is equivalent to using ///.
*
* - Parameter value: The integer to format
* - Returns: A percentage string (e.g. "85%")
*/
func formatPercent(_ value: Int) -> String {
return "\(value)%"
}
// Verify behavior
let scores = [85, 92, 78, 95, 60]
if let avg = calculateAverage(scores) {
print("Average: \(avg)")
}
print(formatPercent(95))
// Empty array case
let empty: [Int] = []
print("Empty: \(calculateAverage(empty) as Any)")
Running the above produces the following output:
$ swift comment_doc.swift Average: 82.0 95% Empty: nil
comment_nested.swift
// comment_nested.swift — Block comments can be nested in Swift.
/* outer comment
/* inner comment */
outer continues — this is valid in Swift (unlike C/C++).
*/
let value = 42
print("value: \(value)")
Running the above produces the following output:
$ swift comment_nested.swift value: 42
Overview
Swift comments fall into two groups: regular comments (// and /* */) and documentation comments (/// and /** */). Swift block comments support nesting, unlike C, which makes it straightforward to comment out a block of code that already contains block comments.
Documentation comments (/// and /** */) support Markdown syntax. Keywords such as - Parameter, - Returns, and - Throws are rendered in dedicated sections of Xcode's Quick Help panel. Swift-DocC can generate a full HTML documentation site from these comments, similar to Apple's own framework documentation. Adding documentation comments to public APIs also makes them visible in Xcode's code completion popover, improving usability for other developers.
If you find any errors or copyright issues, please contact us.