Swift Comments

In computer programming, comments are hints that we use to make our code more understandable.

Comments are completely ignored by the compiler. They are meant for fellow programmers.

There are two ways to add comments in Swift:

  • // - Single Line comments
  • /*...*/ - Multiline Comments

Single Line Comment

In Swift, any line that starts with // is a single line comment. For example,

// create a variable 
var name = "Cartman"

// print the value
print(name)

Here, we have created two single-line comments:

  • // create a variable
  • // print the value

We can also use the single-line comment along with the code.

var name = "swift" // name is a string

Multiline Comment

In Swift, any text between /* and */ is a multiline comment. For example,

/* create a variable
to store salary of employees
*/

var salary = 10000
print(salary)

In the above example, we have used /*...*/ to write the comment that extends for multiple lines.


Use of Swift Comment

1. Make Code Easier to Understand

If we write comments in our code, it will be easier for future reference.

Also, it will be easier for other developers to understand the code.

2. Using Comments for debugging

If we get an error while running the program, we can comment the line of code that causes the error instead of removing it. For example,

print("Swift")

// print("Error Line )

print("UIKit")

Here, print("Error Line) was causing an error so we have changed it as comment. Now, the program runs without any error.

This is how comments can be a valuable debugging tool.

Note: Always use comments to explain why we did something rather than how we did something. Comments shouldn't be the substitute for the way to explain poorly written code.