18. Classes in Swift

In our daily life, we deal with lots of different objects. Some objects are talking with us, some are moving on the road and some are flying on the sky. Naturally we observe everything, we observe the characteristics and behaviours of these objects. For example, one object has some attributes (four wheels, one steering, one engine) and some behaviours (run on the road, apply breaks, turn left/right). On the basis of these observation, we can do the classification of this object, we can say that this object which contains these mentioned attributes and behaviours belongs to class called ‘Car’. 

You can implement these daily life observation in computer programming to solve different problems. Swift provides all object oriented techniques and functionalities to create classes with different attributes and behaviour. A class can contain different type of variables like integer, float and Strings etc, these variables are called attributes or properties of the class. Class can also contain functions, these functions are called behaviour of the class. If you want to declare a class of a person then person attributes can be a name, age, hight, weight etc and person attributes are, person can walk, can talk, can read etc.

Declare a ‘class’ in Swift with { } brackets and properties and functions in it. Here is an example:

class Person {

    // properties
    var name : String 
    var age  : Int 

    // method
    func speak() -> String{
        return ("My name is \(name) and my age is \(age)")
    }
}

Class Person has few properties (age , name) and it contains one behaviour (speak) which returns a string variable. These properties and behaviours are nothing but variables and functions which you are already familiar with.

 

Class initialization

Once you will declare this person class in Xcode with attributes (name, age) and behaviour (speak), you will notice that Swfit will trigger an error “class person has no initializers”. It means that Swift is very strict in variable initialization. You must assign some initial values to variables.

class Person {

    // properties
    var name : String = ""
    var age  : Int    = 0

    // method
    func speak() -> String{
        return ("My name is \(name) and my age is \(age)")
    }
}

Once the error is resolved, now its time initialize the class and create some objects. You can initialize the class as follow

var p1 = Person()

Now p1 is the object of the class, which contains all members (variables, functions) of the class. You can access the class members by using dot operator. Assign some new values to variables and call function or method of class

// Assign values to properties
p1.name = "Khan"
p1.age = 25

// Call method
p1.speak()

Now person name is Khan and age is 25. Speak function will return a string “My name is Khan and age is 25”.

 

Continue with classes ….

 

Download file from GitHub