Swift: The Init Method

Init Method in Swift:

We gave our instances’ properties default values in the previous exercise. If we know that our class instances will differ significantly from one another, we can add an init() method to allow for customization. An init method in Swift is written in the following way:

class Name {
  var property = value ;
  init (property: valueType) {
     self.property = property ;
  }
} ;

The init() method is unique in that it does not require the func keyword and is invoked when an instance is created. Another feature of the init() method is that it uses the self keyword to refer to itself.

Let’s take a look at how init() works:

class Person { 
  var name = "" ; 
  var age = 0 ; 
  var gender = "" ; 

  init (name: String, age: Int, gender: String) {
    self.name = name ;
    self.age = age ;
    self.gender = gender ;
  }
 } ;

So now we can instantiate the Person class and set its properties in a single line:

var teacher = Person(name: "John Dew", age: 34, gender: "Male") ;

It’s worth noting that all properties must have arguments, and the params must be in the same order as the declared properties.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: