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:-
1 |
let <name>:<type> |
Example:-
1 |
let number:Int |
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:-
1 2 |
let <name>:<type> <name> = <value> |
or
1 |
let <name>:<type> = <value> |
Example:-
1 |
let number:Int = 10 |
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:-
1 |
let age, marks: Int |
Example:-
1 2 |
let x = 1, y = 2, z = "Hello, World!" print(z) |
Output:-
1 |
Hello, World! |
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.
Example:-
1 2 3 4 5 6 7 8 9 |
// First Constant let minvalue = 0 // Second Constant let maxvalue = 100 print("1st constant's value is \(minvalue) and 2nd constant's value is \(maxvalue)") |
Output:-
1 |
1st constant's value is 0 and 2nd constant's value is 100 |