3: Variables in Swift

Computers are always work in binary numbers 1 and 0 but humans work with decimal and words. To create a communication between humans and computers we need some medium which can translate human’s instructions into computer’s and computer’s language into human’s understandable medium. This is the point where programming languages come into play. Programming languages allow human to write computer instructions in human readable form so it can be translated into machine understandable format.

One of the most important thing in any programming language including Swift are variables (data types) where human can write some instructions to computer to handle different types of data including numbers, letters, words etc. Variables are in fact locations in memory for storing these data. Variables can be any type, it can be integer type which can hold age or score, it can be string type which can contain name or email address.


Declaring a variable in Swift

In swift, you can declare a variable with keyword “var”.

var name
var emailAddress
var age

You can assign any value to the declared variable and you can change or update the value as well. Type of the variable depends on the value which you will assign to the variable. If you write

var name = "Khan"

It will become string type variable.

var age = 10

it will become integer type of variable.

You can declare boolean variable as well with

var myBoolean = true
var myBoolean = false

 

Once the variable is declared and type is defined by assigning a value, you cannot change data type after that.

Strings variable 

As it is mentioned before that type of the variable depends on the value which you will assign. String variable can be declared like this

var myString = "Hello"

Now myString is a String type of variable, if you will say

myString = 100

Swift will immediately trigger an error that you cannot assign an integer value to string.
Swift also provides a very flexible way to add two strings with + operator.

var myFirstName = "Bob" // String
var myLastName = "Jon" // String

var myFullName = myFirstName + " " + myLastName // Add two strings

 

Integers variable

Declaration of integers are same like String.

// declare integers or numbers
var mynumber = 10
var yournumber = 20

var ournumber = mynumber + yournumber

 

Explicitly declared variable (Type Annotation)

Swift also provides functionalities to declare specific type of variable with type annotation “var name : DataType”

var myInteger   : Int
var myString    : String
var myFloat     : Float

Once variables are declared, you can assign values to them.

myInteger = 10
myString  = "Hello"
myFloat   = 12.123

Swift also allows to declare and define explicit data type at same time.

var myIntAndValue : Int = 10
var myStringAndValue : String = "Hello"

 

Download file from GitHub