19: Swift. Class with init() method

In previous article about classes, you learnt what is class, how to declare and initialize a class and how to access members of the class. Now lets move forward.

init()

You have already notice that Swift force you to assign some initial values to all variables of the class and you can do that like this:

class Person {

    // Assign initial value to class member variables
    var name : String = "" 
    var age  : Int  = 0

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

This task can also be performed by writing init method provided by swift.

init(){
   name = ""
   age = 0
}

Declare variable within class body and Initialize all variables within init method.

class Person {

   var name  
   var age

   // Assign initial value to class member variables with init()
   init(){
      name = ""
      age = 0
   }

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

}

You can notice that once all variables are initialized by using init method, Swift will not throw any error. Now you can create the class object and assign values as normal.

var p1 = Person()
// Assign values to properties
p1.name = "Khan"
p1.age = 25

// Call method
p1.speak()

Notice one thing, in this example you are calling speak method by using class object p1.speak() but you did not call init method. Question is when this init method is called? The answer is, init method is called when you create an object of the class. Following line of code is responsible to call init method

var p1 = Person()

init() with values.

Swift also provides a convenient way to initialize variables while creating class object. Add init function with parameters.

init(personname: String, personage: Int){
   name = personname 
   age = personage
}

Now when you will create an object of the class Person, you can add values at the same time.

class Person {

   var name  
   var age

 
   // Assign initial value to class member variables with init(value,value)
   init(personname: String, personage: Int){
      name = personname
      age =  personage
   }

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

}

Create an object of class Person and call speak function,

// p1 object of person class with 2 values
var p1 = Person("Khan",25)

// Call method
p1.speak()

and output will be “My name is Khan and my age is 25”. One thing is very important to mention that, if your class has more than one init methods, one without parameter and second with parameters. Following line will call init() with no parameters and

var p1 = Person()

if you will create an object with parameters then init(value1,….) with matching parameters will be called.

 

Continue with Classes and inheritance

 


Download file from GitHub