Chapter 6 : Swift Variables



A variable is a storage location name, identified by a memory location , paired with its associative name or identifier having some quantity of information or value.
Swift 4 have below basic variable As discuss in last Chapter – 5

  • Int or Uint
  • Float
  • Double
  • Bool
  • Character

NOTE: There are few more types of variables Array / Dictionaries / Classes/Structures / Optional we will explain them in upcoming chapters



How we use Variable Declaration

Once we declare a variable it tells the compiler how much and where to create the storage of the variable we declare.
we use var keyword for it
Syntax :
var variable_name_here = <initial value>
for e.g.
var varA = 9
print (varA)
It will print 9 as output in console



Type Annotations :
Whenever we declare a variable we need to be specify the type of values the variable can store.

Syntax :
var variable_name : data_type_here = optional_initial_value
for e.g.
var var1 = 5
print(var1)
it will out put : 5

var var2 : Float
var2 = 3.142
print(var2)
it will out put : 3.142



How we Name a Variables ?
The name of a variable is compose of digits, letters and underscore character only.
It never start with a digits.
Its a case sensitive language so upper case letter and lower case letter are treated as different variable names.
NOTE: also we can use unicode character as variable names

for e.g.
var _var1 = “Hello 9to5iOS”
print(_var1)
it will out put :Hello 9to5iOS

print variable use :
We can print the current value of a variable or a constant with this print function, but it need to be interpolate a variable value by wrapping the name with the parentheses and escape it with a backslash before the opening and closing the parent thesis.
for e.g.
var var1 = “9to5iOS”
var var2 =700
print(“value of \(var1) is website name and \(var2) is owner lucky code)

it will out put : value of 9to5iOS is website name and 700 is owner lucky code



Add a Comment

Your email address will not be published. Required fields are marked *