Introduction to Swift Programming

   Apple introduced a new programming language for IOS and OS X developers called Swift. Our Swift tutorial for iOS developers & beginners is a simplified best tutorial for learning swift from basics and gives the clear understanding of apple’s Swift language. Despite the new name, Swift is compatible with the root of its predecessors like C, Objective-C, and Cocoa Touch framework.If you have been programming with Objective-C, learning Swift would be a breeze as it has inherited a number of syntaxes that you may already have been familiar with. And if learning Swift is on your to-do list but you haven’t started yet, We are providing simplified tutorials for learning Swift

We will update this tutorial regularly to add/modify contents. Please visit regularly.


There are few options to have hands on.

1. XCode:

We have to download and install Xcode 8. Once you have installed it, open and select File from the

menu -> New -> Select Source

on the left under either iOS or OS X -> Playground. Give your playground name. That’s it, you are ready to get started.

2. Terminal:

If we have two or more versions of Xcode installed then you will need to select Xcode 6 and above as our default version. If we are using Xcode 6 and above only, then skip this step and ahead to step 3, otherwise go ahead and run the following line:

sudo xcode-select -s /Applications/

Please check your app name in the “Applications” folder to write out the appropriate path when using xcode-select.

3. To start the REPL type:

xcrun swift

3. Online compiler for learning Swift

 Go to the below site, it has an online compiler for swift.


Variables & constants in Swift is a basic and fundamental concept. This tutorial is focusing on explaining let(immutable) & var(mutable) declaration. Both variable and constant two terms are self-explanatory, Constant refers to the values which never gets changed during runtime. Whereas Variable refers to the values, which can be changed during runtime.

Declaring a Constant:

let is the keyword, used to declare the constants.

let myName = “ABCD” and let age = 20

var is the keyword , used to declare the variables.

var salary= 2000;

You can change the value of this salary variable since it is declared with var keyword. whereas you can’t change the age since it is declared with let keyword.

for ex:-

salary = 3000 // works fine

age = 22 // compile error

Note: Though it is not mandatory to terminate the line with a semicolon in swift. You can use semicolon to write multiple lines in single line . ex let a = 90; var b = 100 

We will see variables & constants in detail in data type & Tuples


Swift Tuples

Tuples are similar to collection datatypes like array and dictionaries. Tuples can contain values of any data type. Then, the difference between collection and tuple is, we can not add or delete an element from a tuple.

Do you wanna know the syntax and how it should be declared. Generally, Tuples are defined as a comma separated values, within a pair of parentheses.
let nameAndAge = (“Tom Tom “, 41)  
The (“Tom Tom”,41) tuple groups together a String and an Int to give the name and age of a person.
It can be described as “a tuple of type (String, Int)”.
You can create tuples from any permutation of data types, and they can contain many different data types as you like. There’s nothing stopping you from having a tuple of type (Int, Int, Int), or (String, Bool), or indeed any other permutation you require.

When to Use a Tuple:

Tuples are particularly useful as the return value of a function. A function that tries to retrieve a web page might return the (Int, String) tuple type to describe the success or failure of the page retrieval. By returning a tuple with two distinct values, each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type.

Decomposing and accessing values from a Tuple:

We can decompose a tuple’s contents into separate constants or variables, later we then access it as usual:
let  (name,age) = nameAndAge  // to know more about let , please visit variables in swift3
println(“Age is \(age)”)
// prints “Age is 41”
println(“Name is \(name)”)
// prints “Name is Tom Tom”
Access the individual element values in a tuple using index numbers starting at zero:
println(“Name  is \(nameAndAge .0)”)
// prints “Name is Tom Tom”
println(“Age is \(nameAndAge .1)”)
// prints “Age is 41”

Alternatively, We can name the individual elements in a tuple when the tuple is defined like below,

let nameAndAge = (name : “Tom Tom”,age:41)
If we name the elements in a tuple, we can use the element names to access the values of those elements,
println(“Name is \(”)
// prints “Name is Tom Tom”
println(“Age is \(nameAndAge.age)”)
// prints “Age is 41”

Note: If we need only some of the tuple’s values, then we can ignore parts of the tuple with an underscore (_) when we decompose the tuple:
let (name, _) = nameAndAge

Swift operators

As we all know operators are the basic and fundamental concepts in any programming languages. In Swift, operators are same as other programming language operators, but Swift operators are more efficient and simplified than other languages which help developers using it efficiently. let’s go through operators, then on the go lets see the swift specific operators. Is it boring? if so, please bear with me.

For what we need operators and what is the purpose of it?. Simple, manipulating the values and checking the multiple variables and decide the flow of the code using decision-making syntax.

Operators are Unary, binary and ternary.

Unary Operator:

Unary operators work on a variable. Explaining by words will rotate our brain in 360 degrees. right.. let’s see an example for unary operators
lets say boolean variable ‘a’ is there, and we want to change the state of it, like true to false or vice versa.
a = !a
So here, ‘!’  is an unary operator, which operands on a variable named ‘a’.
a = -a
where, ‘-‘ operator changes it to a negative value if it is positive.

Hope that at this moment you could get the idea of binary operator

Binary Operator:

Nothing to explain in detail, as unary operator works on a single variable, a binary operator has two operands, wanna put one technical word, that’s why operands. So binary works on two variables like below
Addition -> a = a + b
Subtraction -> a = a - b
Multiplication -> a = a * b
Division -> a = a / b
Modulo -> a = a % b
Hope that, you can easily point the binary operators on the sample above, yes +,-,/,*% are the binary operators.

Ternary Operators:

Now hope that I need not explain about ternary operators, if I say again, like if an operator works on three operands then it is a ternary operator. You will throw a stone on me. But the sad part I have to say the same. please pick the small one. let’s see an example for that.

‘? :’ is a ternary operator, let’s take an example, we need to check the boolean, we need to print as true if it is true, or false if it is false.
how we will do generally using if condition.
Bool b = false
if b == true {
print("yes, it is true")
print("no,it is false")
We have written six lines for that, how it would be if we use ternary operator and write the above case in a line. Simply superb right!!
(b == false) ? print(“yes,it is false”) : print(“no,it is false”)

Assignment Operator:

The assignment operator is to initialize or update the value of a variable.
below is an example for that let b = 10
As I said in the beginning of this tutorial, I am pointing the difference of assignment operator between C, objective C, and Swift.

in objective C
if a = b {
} // is valid, since it will return a value after assigning the value of b to a, but in Swift, the same condition is not valid since assignment operator in Swift never returns a value.

Arithmetic Operators:

Swift supports the four standard arithmetic operators
addition +
subtraction –
multiplication *
division /

Another significant thing in swift, I like to highlight here is, addition + operator also supports for String concatenation. we can see String in detail in next chapter.

Comparison Operators:

Like other programming languages, Swift supports following standard Comparison operators.

equal to (a == b )
not equal to (a != b )
less than (a < b)

greater than ( a > b)
less than or equal to ( a b)
greater than or equal to ( a b )

Identity operator:

Swift also provides identity operators which help to test whether two object references both refer to the same object instance.

Range operators:

Range operators are expressing of the range of values. Swift provides two type of range operators.

Closed Range operator
Half-Open Range operator.

Closed Range operator:

The syntax for closed range operators is a…b, it includes both a and b

for i in 1...5{
print(" i = \(i)")

Half Open Range Operator:

The half-open range operator( a..<b ) also defines a range that includes a but not includes b.

for i in 1..<5{
print(" i = \(i)")

the above example does not print the 5th value, as it does not include 5 in the range.

Logical operator:

Swift supports standard logical operators,
|| or operator
&& and operator

Nil-Coalescing Operator:

?? is nil coalescing operator, so what it does, it unwraps the variable to know the value and use it. If it does not have value, it sets nil. I can read your mind voice that expecting an example.

Lets assume

var a : String?

let b = a ?? “a is nil”

from the above example, our Nil-Coalescing operator checks the value of string a by unwrapping it and assign that value to b, if a is nil while unwrapping, it sets string as “a is nil” to b.

This is nice right, we read ternary operator to make use of if condition efficiently, now we are having a Nil-Coalescing operator which is more elegant way to encapsulate this conditional checking.

Force UnWrapping, Optional Chaining , Optional Binding – Swift 3

Before learning optional , it would have been better, if we have gone through Variables in Swift before.

Wrapping , UnWrapping in Swift

Optional values are the fundamental concept in Swift language, if a variable ends with ‘?’ in declaration, then it is an optional value(wrapping). Meaning of that it may or may not contain value for that. Bit confusing? lets see an example

let normalString : String = “variable without optional”

We have declared a constant string variable without optional ‘?’ , while printing below


it writes as “variable without optional“, now let’s see what happens if we use optional ‘?’

let optionalString : String? = “String variable with optional”


It prints as “Optional(“String variable with optional”). Hope that you can see the difference. Yes, Optional ‘?’ wraps the actual value, and if we need actual value of that variable, we need to unwrap it using ‘!’ , 


 Now it prints as “String variable with optional”. I hope that now you got idea wrapping and unwrapping.

Force unwrapping:

Force unwrapping is nothing but an extracting the values from an optional ‘?’ variable . Ok, we aware that force unwrapping using exclamation mark ‘!’ will return a value. But how it will behave if it does not contain a value. Yes, it will make the application crash at run time. let’s see an example for that

var optionalString : String? // not assigning any value to this string data type

print(optionalString!) // here force unwrapping it.

then, the result in a playground is

fatal error: unexpectedly found nil while unwrapping an Optional value

Now we all got idea about wrapping(‘?’)  , unwrapping(‘!’) and now you will have a question, What is the purpose of it? and where can we use it efficiently?. That’s where optional chaining and optional binding comes.

Optional Chaining and Optional Binding:

let’s assume that we don’t have an optional feature in Swift, and I am creating an instance as ‘a’ for the class named ‘A’ like below. But I am not initializing it properly, just declaring it.

class A{

    let: String = "property in class A"    


let a : A

and I am accessing the property called ‘p’ which is there in that class ‘A’


Now the playground gives me error and crashing with error

Optional chaining in Swift 3
Optional chaining in swift3

Playground execution failed: error: MyPlayground.playground:15:7: error: constant ‘a’ used before being initialized

Optional helps us to avoid this error and is playing a key role here. It avoids the app crashing at runtime though we forget to initialize the class object instance. Let’s take the same example again but with optional

class A{

    let: String = "property in class A"    


var a : A?

I am accessing the property called ‘p’ which is there in that class ‘A’


Now the app won’t crash, but it will print as ‘nil’. This feature in Swift is optional chaining. in the same case, if we do force wrapping it print(a!.p) without initialize then the app will crash.

We now have basic knowledge on optional chaining, wrapping, force unwrapping then what is that optional Binding?.

Optional Binding:

Optional Binding is to get the value from an optional variable to normal variable. let’s take a look at this example

var optionalString : String? = "String with '?' optional" // declaring optional string with value not nil

print(optionalString) // printing it without unwrapping , prints as “Optional(“String with \\’?\\’ optional”)\n”

if let getValue = optionalString { // here , we are getting the value from optionalString to getValue , i.e Optional Binding.

    print(getValue) // if value is there , then prints as "String with '?' optional"



print("value is not there in optionalString") // if value is there , then prints as "value is not there in optionalString"


Hope that you have understood Optional Binding, Optional chaining, wrapping ‘?’ , force unwrapping ‘!’ in swift. Please share this tutorial across your circles and put your thoughts in the comment section as well.

Swift String Concepts

String is the special data type in programming languages, the sequence of characters is String. In Swift string variables are declared using String syntax.

And character is an element in String which is an another data type in a programming language.  In swift, character syntax is Character. Ok, don’t worry I won’t leave you without telling an example for that.You will get an example in the String mutability section.

Mutable, Immutable String:

String mutability is, how we can alter the string variable. if a string is declared with var keyword if you want to get to know about var and let, please check our variable and constants tutorial. Let’s come back to our point. If a string variable is declared with var keyword, then it is a mutable string which means we can change the value of that variable at any time like we have NSMutableString in Objective C. In Swift it is very simple right.

just declare as

var mutableString : String = “Mutable string as a keyword is var”

whereas if a string is declared with let keyword string, then it is constant and we can not change the value of that string object.

let immutableString: String = “String can not be modified”

This is just similar to NSString in Objective C.

if we try to change the value of the string, the compiler will throw an error.

immutableString = “modifying constant String” // compiler error for modifying constants.

whereas we can change the value of mutable string which is having var keyword.

mutableString = “i am able to modify var string” // compiler not saying any error.

Characters In String:

As we states earlier,string is a collection of characters , we can access characters in a string using for-in . I will write tutorial about for-in in control flow chapter soon.

let myString = “characters list”

for c in myString {

print(\(c)) // it prints character in that string one by one.


String interpolation:

String interpolation is nothing , constructing a string from multiple data type like int,character or other literal. Below is an example for that.

let interpolationStr = \(3) + \(2) = \(5)”

print(interpolationStr) // prints 3 + 2 = 5

where, 3 , 2 and 5 are Int.

String concatenation:

String concatenation is very simple in Swift, we have already mentioned this in operators chapter. Arithmetic plus ‘+’ operator can be used for string concatenation.

let concatString = “string1” + “string2”

print(\(concatString)) // prints as string1string2 as + concatenates both strings.

Is Swift String Unicode compliant?

Unicode is an International standard format, if a text file is not supporting that then it will not be recognized by other programming languages. It clears that Unicode is for reading, encoding text from different writing systems. Swift is also Unicode compliant.

How does this Unicode work? Unicode has some background strategy that each character will have a scalar value that is Unicode scalar. For example, U+0061 is for ‘a’.

Modifying the String:

Swift provides a couple of options to access or modify the strings. It could be either through methods or subscript.

First of all, we need to initialize the string,

let myFirstString = “”

let myString = String()

In both ways we can initiate the string, both are equal and has an empty string.

Empty String:

Swift provides a method to check if the string is empty or not. Below is an example for that

if myString.isEmpty {

    print(“String is Empty”)


isEmpty() method is used to check the empty string.

String Indices:

As we all know, the index is for pointing the position. Since string in a collection of characters, String has a property called index. An index gives the position of that character.

Three key points , we should keep in mind are startIndex , endIndex, offSetBy. Let me explain one by one .

startIndex gives you the first character position of the String, for example

let myString = “abcde”

if myString.isEmpty {

    print(“String is Empty”)


print(\(myString[myString.startIndex])”) // prints a

As String is a collection of characters , we are getting the first index using startIndex and accessing the first character from the String.

endIndex gives you the last character position of the String, for example

let myString = "abcde"

if myString.isEmpty {

    print("String is Empty")


print("\(myString[myString.endIndex])") // prints e

As String is a collection of characters, we are getting the last index using endIndex and accessing the last character from the String.

Note: please keep in mind that we can not access a character in String using integers

Thats why our next key word offSetBy comes here, which advances the index position from startIndex in the below example

print(\(myString[myString.index(myString.startIndex, offsetBy: 3)])”

Swift String index and empty

The above print statement prints ‘d’ , since we are setting the offset value 3 from startIndex.

Hope that I have given the basic stuff about String in Swift. Please share and raise your feedback in comments

Collection Types in Swift

I am starting this Collection Type tutorial in the assumption that you have knowledge on Datatypes like int, string. If you want to refresh, please go through our Datatypes and String tutorial.

Lets come back to Swift Collection, it is used to store multiple values of the same type in a type. There are three types of collection in Swift 3.

  1. Arrays
  2. Set
  3. Dictionary

Arrays elements are ordered collection type, whereas Set and Dictionary are unordered collection ttypes,elements in Set and Dictionary are not ordered.

Another difference between Array and Set is, Array can have duplicated elements , but values are unique in Set.


As we said earlier, an array is an ordered collection type, and it can have same values in multiple index i.e duplicated values.

and declaration is Array<Element>, where Element is a type of the value that array is holding. We will see an example in next section.

Array Initialisation:

If you are from String tutorial in our last chapter, this will be easier for you to understand all the initialisation in Swift.

let myFirstArray : Array<Int> = [1,2,3,4]

in shorthand , we can initialize an array as  

let myFirstArray = [1,2,3,4]

Those two examples are constant arrays and we can not modify it since its keyword is declared as let.

Below is an example of creating an empty array and followed by its shorthand.

var mutableFirstArr = [Int]()

var mutableFirstArr = [] // shorthand empty array

Since it is declared with var, it is mutable and we can modify this array values at any time.

Accessing Arrays:

Accessing array is nothing but a getting the number of element from that array, get the value from particular index, modify the value at particular index, add or remove a value to/from an array

Let’s start with count,  let’s take our previous example back here

let myFirstArray = [1,2,3,4]

The number of elements that array stored can be read by count method.

print(myFirstArray.count) , it prints as 4, since it has 4 values such as 1,2,3,4

Empty Array:

To determine the empty state of an array, we can use count method again, if it is zero, then the array is not having any values.

Another simple method is there in Swift, isEmpty, to check the empty array. Here no need to check the count is equal to 0 or not, pretty simple right?.

if myFirstArray.isEmpty {

  print("array is empty")


else {

    print("array is not empty")


Add & Delete :

Another key factor in a programming language is to add an element of an array. append() in Swift help us to add a new value to an existing array at the end. Let’s take the same array but with var keyword, since we are going to change it by adding a value.

var mutableFirstArr = [1,2,3,4]


Here I am appending number 5 at end of the array.

Alternatively, we can join two compatible type arrays using + operator easily.

mutableFirstArr += [6]

in the above line, I am adding an array that has single int element as 6 to an existing array.

We have knowledge now to add a value at the end, so next is to add value at the particular index.

mutableFirstArr.insert(0, at: 0)

The above example explains the insert method and takes an argument with at label that is the index position to insert the value in that array. Ok, Next thought in your mind would be deleting a value from an array. Am I right?

mutableFirstArr.remove(at: 5)

remove method that takes index position to delete the value from that position.

another short form to delete the last element of an array is removeLast().

Accessing array using Subscript:

To read or change a value from a particular position of an array, subscript syntax can be used. It is very simple to use.

mutableFirstArr[5] = 6

The above example replaces the value that is at the 5th position to a new value as 6.

Below is playground screenshot to brief our array tutorial.

Screen Shot 2017 04 15 at 10 27 54 PM

Array iteration:

An array can be iterated using for-in loops that we will see in future.

for i in mutableFirstArr{




Set in swift is more or less similar to an array. But the main difference between an array and a set is, duplicated values are not allowed in Set. And Set also performs set operations like join, intersection, union, symmetric difference.

The types that are going to be stored in Set must be hashable, in order to compute its unique value internally. If a type is not hashable, it can not be stored in Set.

Set Initialisation:

Set initialization is similar to Array, here also we have different types of initialization.

let myFirstSet : Set<Int> = [1,2,3]

let mySet = [1,2,3]

var firstSet = Set<Int>() 

Since we have explained this initialisation in Array section, assume that need not to explain again. “I am bit lazy 🙂 “

Accessing and Modifying a Set:

Set can be accessed using its methods and properties.

count property is to find out the number of items or elements in a set


Just like array, Empty set can be found using isEmpty property

if myFirstSet.isEmpty


    print("set is empty")


else {

    print("set is not empty")


Add or remove an item:

Insert method is useful for inserting an item in an existing set, It is similar to an array, but the difference here in insert method of a set is, it won’t ask you the index position to where it needs to be placed. Can you guess that why it is like that? yep, Set is an unordered collection type, and it places the item at any place.

var firstSet = Set<Int>()


And to delete an item is also same,


Set iteration:

Set also can be traversed through using for-in loops.

for i in firstSet{



Playground screenshot for giving a brief about Set.
Screen Shot 2017 04 15 at 11 15 24 PM

I will write detail tutorial for dictionaries in next chapter. Please share this tutorial if you feel that I have given at least some basic knowledge,  across your friends in social media and put your words in comment section to improve my skills

Dictionary – Swift 3

Dictionary is an another container/collection type in Swift.This tutorial gives the basic understanding of Dictionary or key value type.  Dictionary and Set both collection types are unordered types whereas Array is an ordered type, items in an array are in an order. Like String or Array, Dictionary tutorial also briefs initialization, declaration, accessing and modifying the dictionary.

“Dictionary is a key value pair data type, each value in a dictionary is associated with a unique value”. This key helps to access the value from the dictionary. And the items or elements in a dictionary can be in any order.

Dictionary Initialization:

Just like other types in Swift, Dictionary also has inferred and explicit declaration.

Below example does not specify its key, value type explicitly. Hence this type of declaration is inferred.

let inferredDict = ["gender" : "male" , "name" : "ProgramTeach"]

 The above declaration initializes the dictionary with two items. As both values in the dictionary are a String type, the compiler is not prompting the error to specify the type. let’s add age with Integer type value in the sample.

let inferredDict = ["gender" : "male" , "name" : "ProgramTeach" , "age" : 21] as [String : Any]

if you see the colored casting is to let the compiler know the type is dictionary having generic values. The below declaration is equal to that where we are explicitly specifying the Generic type in front.

let inferredDict :  [String : Any] = ["gender" : "male" , "name" : "ProgramTeach" , "age" : 21]

Dictionary Mutability:

Mutability is same as we have NSMutableDictionary and NSDictionary in Objective C. If a dictionary declared with let keyword, it is constant and its values can not be modified. The above samples are declared with let keyword. If a dictionary is declared with var keyword, it is mutable and value of that dictionary can be modified, new key value can also be inserted.

var inferredDict :  [String : Any] = ["gender" : "male" , "name" : "ProgramTeach" , "age" : 21] // now the keyword is var. 

We will extend this in next section called accessing / Modifying the dictionary:

Accessing a Dictionary:

As we said earlier, a unique key is to access the value from a dictionary as a subscript.

The returned value is optional since it may have value or not, Below optional binding helps to check value presence.

if let age = inferredDict["age"]{



else {

    print("age is not there")


There we are reading the age from that dictionary, if it has value for that key, it gives value.

Modifying a Dictionary:

Dictionary with var keyword is mutable. We can add, update or delete an item from the dictionary.

var firstDict :  [String : Any] = ["gender" : "male" , "name" : "ProgramTeach" , "age" : 21]

firstDict["age"] = 31 // updates the age

firstDict["address"] = "ProgramTeach , no 6 xyz street" // adds new entry to that dictionary

firstDict.removeValue(forKey: "gender") // removes an item gender from dictionary.

Empty Dictionary:

Empty dictionary means instance with zero entries that can be identified using isEmpty property.

if firstDict.isEmpty {

    print("empty dictionary")


To create empty Dictionary,

let emptyDict : Dictionary<String,String> = Dictionary<String,String>()

let shortEmptyDict = [String:String]() // short form

Playground screenshot for covering this tutorial.

Swift Dictionary

Please share and drop your thoughts in comment section.

Classes & Structure in Swift

Classes and Structures in programming language are two important concepts. Both are useful for building the block of codes and both can have properties and methods. Unlike other programming languages, Swift does not require you to create a separate interface and implementation file. Both interface and implementation can be in a single swift file.

Class and structure have some unique features.

  1. Properties to store values.
  2. Methods to provide functionality
  3. Both can be extended to extend the functionality
  4. Subscripts to access the values
  5. Conform to protocols to provide standard functionality
  6. Initialisers are to set up their initial values

Ok, let’s see what are the significant differences between Structure and class.

  1. Classes have the inheritance properties which make one class can inherit the characteristics from other class. Whereas structure does not have inheritance.
  2. Classes are the reference type, whereas structures are the value type.
  3. Classes have the de-initializer which helps to free up the memory.
  4. Typecasting can be done in classes that will help to identify the class type at runtime.


Both Classes and structures have the same syntax like below.

// Class syntax

class className {

    //properties and methods


// Structure  syntax

struct structName {  

  //properties and methods


class and struct are the keywords.


struct Rectangle {  

  var x = 0    

  var y = 0  

  var width = 100  

  var height = 100


class Rectangle {  

  var x = 0    

  var y = 0  

  var width = 100  

  var height = 100


Class and Structure Instances:

Initialization is the first step to prepare class, structure, and enumeration for use. Initial values can be set during object initialization. Unlike structures and Enumeration classes have de-initializer along with initializer to free up the memory.

let rectangle = Rectangle() // is the initialization for the structure and class

Structures can set the default value while creating an instance for that structure. it can be called as memberwise Initializers

let rectangle = Rectangle(x: 10, y: 10, width: 1000, height: 1000) // it sets the default value to the stored properites such as x, y, width and height.

Accessing Properties:

Properties are in the classes and structures can be accessed using dot(.) syntax based on their access control(private, fileprivate, internal, public).

print("The width of rectangle is \(rectangle.width)")

Complete sample code is here

struct Rectangle {    

var x = 0    

var y = 0    

var width = 100    

var height = 100

let rectangle = Rectangle(x: 10, y: 10, width: 1000, height:1000)

print("The width of rectangle is \(rectangle.width))


class Rectangle {

    let x = 0

    let y = 0

    let width = 100

    let height = 100


let rectangle = Rectangle()

print("The width of rectangle is \(rectangle.width)")

Identity Operators:

We have a dedicated tutorial for swift operators . But explaining about Identity operators here should be the best.  As classes are reference types, properties of different instances of a class may have the same reference in backside. So identity operator helps to check if two or more variables or constants linked to the same reference of a class or not.

=== (three equals) is to check identical and !== is to check not identical

See you on next tutorial, please do sharing and motivate us to write more efficiently.

Methods in Swift

Methods are functions which do functionality and task. Classes, Structures, and Enumeration can all have methods or functions in Swift. We all aware of that Structures and Enumerations in Objective C cannot define methods. Swift has a nice ability to define functions in Structure and Enumeration Type.

Two types methods are there in Swift just like other programming languages.

  1. Instance Method
  2.  Type Method or Class Method

Instance Methods:

Instance methods can be accessed through the object or instance of a particular class, structure or enumeration which means it belongs to the particular class, structure or enumeration type. An instance method can access properties and other instance methods of the same type. Instance method should be declared within the scope of its type. (between { and } of the class, structure or enumeration).

class Rectangle {

    let x = 0

    let y = 0

    let width = 100

    let height = 100

    func calculateArea() -> Int { // Instance method

        return width * height



let rectangle = Rectangle() // Instance of the class, 

print("The area of a rectangle is \(rectangle.calculateArea)")

‘CalculateArea’ is an instance method which calculates the area of a rectangle. This method is accessed by an instance of a class.

Type Methods:

Swift has another type of method called Type Methods that can be accessed by using the type, not by the instance of the type. ‘static’ keyword in Swift is used to define Type Methods. Classes can also use ‘class’ keyword to allow its subclasses to override this method. Both instance method and type method use dot(.) syntax to access. But the major difference is instance methods are accessible by self or by the instance of that type whereas Type methods are accessible by Type itself.  To simplify our explanation below is the same sample code we have come across while studying instance method. Now we are just adding an extra method as classMethod with the static keyword.

class Rectangle {

    let x = 0

    let y = 0

    let width = 100

    let height = 100

    func calculateArea() -> Int {

        return width * height


    static func classMethod() { //Type Method 

        print(“i am a type or Class method”)



let rectangle = Rectangle()

print(“The area of a rectangle is \(rectangle.calculateArea)”) // accessing instance method

Rectangle.classMethod() // accessing class method.