0
0
Swiftprogramming~5 mins

Comments and documentation markup in Swift

Choose your learning style9 modes available
Introduction

Comments help explain your code so others (and you) can understand it later. Documentation markup creates helpful notes that tools can show nicely.

When you want to explain why a piece of code exists.
When you want to remind yourself what a function does.
When you want to create clear instructions for others using your code.
When you want to add notes that show up in code completion or documentation tools.
When you want to temporarily disable code without deleting it.
Syntax
Swift
// This is a single-line comment
/* This is a
   multi-line comment */
/// This is a documentation comment for a function
/**
 This is a multi-line documentation comment
 for describing a function or type
*/

Single-line comments start with // and go to the end of the line.

Multi-line comments start with /* and end with */. They can span many lines.

Examples
A simple single-line comment before a print statement.
Swift
// This prints a greeting
print("Hello")
A multi-line comment that can explain more details.
Swift
/*
 This is a longer comment
 that explains multiple lines
*/
print("Hi")
A documentation comment that describes what the function does. Tools can show this info.
Swift
/// Adds two numbers and returns the result
func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}
A multi-line documentation comment with parameters and return description.
Swift
/**
 Calculates the area of a rectangle.
 - Parameters:
   - width: The width of the rectangle.
   - height: The height of the rectangle.
 - Returns: The area as an Int.
*/
func area(width: Int, height: Int) -> Int {
    return width * height
}
Sample Program

This program shows how to use documentation comments to describe a function and regular comments inside the function. It then calls the function and prints the greeting.

Swift
/// Greets the user by name
/// - Parameter name: The name of the user
/// - Returns: A greeting string
func greet(name: String) -> String {
    // Create the greeting message
    let message = "Hello, \(name)!"
    return message
}

// Call the function and print the result
print(greet(name: "Alice"))
OutputSuccess
Important Notes

Use comments to explain why something is done, not just what the code does.

Keep comments short and clear to avoid confusion.

Documentation comments (/// or /** */) help tools generate helpful guides and autocomplete info.

Summary

Comments make code easier to understand for you and others.

Use single-line (//) for short notes and multi-line (/* */) for longer explanations.

Documentation comments (/// or /** */) describe functions and types for tools and users.