Swift Constants

In this tutorial you will learn about the Swift Constants and its application with practical example.

Swift Constants

Constants are basically immutable literals whose values cannot be modified or changed during the execution of program.

Declaring Constants In Swift

The Constants are created in the same way you create variables but instead of using the var keyword here we use the let keyword and by convention constant names are always preferred in uppercase.

Syntax:-

Example:-

Here, we have declared a constant called number which is of type Int.

Initializing Constants

The assignment operator (=) is used to assign values to a constants, the operand in the left side of the assignment operator (=) indicates the name of the constant and the operand in the right side of the assignment operator (=) indicates the value to be stored in that constant.

Syntax:-

or

Example:-

Here, we have declared a constant called number which is of type Int with value of 10.

Declaring and Initializing Multiple Constants

In Swift, it is possible to define multiple constants of same type in a single statement separated by commas, with a single type annotation after the final constant name as following-

Example:-

Example:-

Output:-

Printing Constants

In Swift, print() function is used to print the current value of a constant. String interpolation can be done by wrapping the constant name as placeholder in parentheses and escape it with a backslash before the opening parenthesis. Swift compiler replaces placeholder with the current value of corresponding constant.

Recommended:-  Swift For in Loop

Example:-

Output:-

In this tutorial we have learn about the Swift Constants and its application with practical example. I hope you will like this tutorial.