iOS Development with Swift 2 - Variables

A variable is a memory / storage that our program can use to store and manipulate data. Each variable has a specific data type, which determines the size that a variable will occupy in memory.

Swift provides the following data types −

  • Int − Used to store integer / Whole numbers within our program.

  • Double − This is used to store large floating (64-bit) values, e.g. -378.878.

  • Float − This is used to store small floating values. E.g. 3.14

  • Char (character) − This is used to store a single character. E.g. ‘A’

  • String − This is a collection of characters. E.g. – “This is String”.

  • Bool − This data type is used to store a value in true or false only.

Swift also allows using other Data types such as −

  • Arrays
  • Dictionaries
  • Classes
  • Structures
  • Optionals

All of these will be discussed in the subsequent chapters.

Variable Declaration

Variable declaration is used to declare a variable i.e. allot space to that variable in the memory. To declare a variable in swift, we need to use a keyword, var.

var variableName = Initial Value   
var x = 10 or var x = "Hello" 
// We can use this method of declaration if we   
// don’t know that kind of data will be stored. 
var variableName : Data type = Initial Value  
// if we know the data type. 
Var x: Int = 10    
// can only store integer type of data

As shown above, we can add any number of variables to our code in any of the above method, whichever is suitable for our use.

Kickstart Your Career

Get certified by completing the course

Get Started