Comments help explain your code so others (and you) can understand it later. Documentation markup creates helpful notes that tools can show nicely.
Comments and documentation markup in 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.
// This prints a greeting print("Hello")
/* This is a longer comment that explains multiple lines */ print("Hi")
/// Adds two numbers and returns the result func add(_ a: Int, _ b: Int) -> Int { return a + b }
/** 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 }
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.
/// 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"))
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.
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.