2
2
.
.
3
3
.
.
1
1
C
C
o
o
n
n
s
s
t
t
a
a
n
n
t
t
s
s
I
I
n
n
f
f
o
o
Constant has value which cannot be changed once it is set (unlike Variable which can change its value multiple times)
Referencing Constant that has no Value gives error: constant 'age' used before being initialized.
This is because only Optional Constants are allowed to be nil. This is why Optionals were introduced in the first place to
detect these kind of errors at compile time rather than during run time.
C
C
o
o
n
n
s
s
t
t
a
a
n
n
t
t
S
S
y
y
n
n
t
t
a
a
x
x
Constant is declared by
using required Keyword let
followed by required Constant's Name name
followed by optional Constant's Data Type String (Optional only if Value is given from which it can be inferred)
followed by optional Constant's Value "John"
E
E
x
x
a
a
m
m
p
p
l
l
e
e
In this example we declare
Constant name by specifying Data Type as String and by giving it an initial value of "John"
Constant age by specifying Data Type as Int since no initial Value was given from which Type could be inferred
Constant weight by omitting Data Type since it can be inferred as Int from the given initial Value of 180
Constant Syntax
//DECLARE CONSTANT.
let name : String = "John" //Full Syntax with both Data Type and initial value
let age : Int //Must Declare Data Type since there is no initial value
let weight = 180 //Data Type can be ommited since it is infered from initial value
//ASSIGN NEW VALUE TO CONSTANT.
age = 20 //Constant's value can be set only once
//age = 30 //This line would throw error since we are trying to change value of a Constant
//DISPLAY CONSTANT.
print(age)