Comments explain single or multiple lines of code. They are written for developers to better understand the code and are ignored at runtime.

In Swift, you can write comments in various ways, including:

  • Single-line comments
  • Multi-line comments
  • Documentation comments

Swift comments resemble C comments, and it’s considered good practice to include comments in the following blocks or lines of code:

  • Class descriptions
  • Before method declarations
  • Any complex logic code
  • Documentation comments

Single Line comments in Swift

Single-line comments provide a description or additional context for a single line of code. They can be placed anywhere within a line.

These are also known as inline comments. They always start with double forward slashes (//) and end with a line break.

Syntax:

// This is single line comments in Swift Code

Example

hello.swift:

// Hello World application
print("Hello World application")

After learning single-line comments, let’s explore how to write multi-line comments.

Multi-line Comments in Swift

These comments span multiple lines and are also referred to as block comments. They begin with /* and end with */.

/* multi line comments 1
 Multi-line comments 2
 multi line comments 3
 */

Alternatively, you can use the single-line comment syntax to create multi-line comments.

// multi line comments 1
// multi line comments 2
// multi line comments 3

This allows you to write multiple lines of code without the compiler interpreting them.

Block level comments in Swift Example:

// Hello world sample program
// Basic program to print hello world to the console
/* First code to write in Swift programming language */

    print("Hello World app");

Conclusion

You have learned about the different types of comments in the Swift programming language.

  • Single-line comments (//)
  • Multi-line comments (starting with /* and ending with */)