A comment is a programmer-readable explanation or annotation in the source code of a program. It is ignored by the compiler when the code is compiled.
Comments are intended for person reading the code to better understand the intent and functionality of the program. It can be helpful while working on a team to clarify the purpose of the code for other team members or while working solely it can act as a reminder to own.
In swift there are two types of comments:
In Swift, any line starting with two slashes
// is a single line comment.Everything starting with two slashes
// is ignored by the compiler.
You can find a simple example at the top of the playground:
//: Playground - noun: a place where people can play
It starts with two slashes
// and provides meaningful explanation of the file as ": Playground - noun: a place where people can play".
//Sample program //stores 3.14 in variable pi let pi = 3.14159 print(pi)
The above example contains two single line comment:
// Sample program // stores 3.14 in variable pi
If your comment includes multiple line, you can enclose it inside
Multiline comments start with a forward-slash followed by an asterisk (
/*) and end with an asterisk followed by a forward-slash (
*/). Everything in between
*/ is ignored by the swift compiler.
/* This is a multiline comment. After you write multiline comment add * following by / to end it */
/* Hardcoded pi value may be less accurate. So you can calculate using in built data types for more accurate value */ let pi = Double.pi print(pi)
The above example contains a multiline comment.
/* Hardcoded pi value may be less accurate. So you can calculate using in built data types for more accurate value */
Although comments are meaningful to better understand the intent of the code written. Here are things you need to consider while writing it:
//This is a comment. //Use it when necessary and preciselyThe above way to write comment is correct but not recommended because you need to write multiline comments if the comment is greater than one line. The better way to write is using multiline comment as:
/* This is a comment. Use it when necessary and precisely */
let pi = 3.14159 //stores 3.14 in variable piThis way to write comments is valid. But it's better to write comment in a separate line as:
//stores 3.14 in variable pi let pi = 3.14159