2
2
.
.
2
2
.
.
2
2
V
V
a
a
r
r
i
i
a
a
b
b
l
l
e
e
s
s
I
I
n
n
f
f
o
o
Variable has value which can be changed any number of times (unlike Constants which always hold initial value).
Referencing Variable that has no Value gives error: variable 'age' must be initialized.
This is because only Optional Variables 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.
V
V
a
a
r
r
i
i
a
a
b
b
l
l
e
e
S
S
y
y
n
n
t
t
a
a
x
x
[
[
R
R
]
]
Variable is declared by
using required Keyword var var
followed by required Variable's Name name
followed by optional Variable's Data Type String (Optional only if Value is given from which it can be inferred)
followed by optional Variable's Value "John"
E
E
x
x
a
a
m
m
p
p
l
l
e
e
In this example we declare
Variable name by specifying Data Type as String and by giving it an initial value of "John"
Variable age by specifying Data Type as Int since no initial Value was given from which Type could be inferred
Variable weight by omitting Data Type since it can be inferred as Int from the given initial Value of 180
Variable Syntax
//DECLARE VARIABLE.
var name : String = "John" //Full Syntax with both Data Type and initial value
var age : Int //Must Declare Data Type since there is no initial value
var weight = 180 //Data Type can be ommited since it can be inferred as Int from initial value
//ASSIGN NEW VALUE TO VARIABLE.
age = 20 //Variable's value can be changed any number of times
//DISPLAY VARIABLE.
print(name)