Swift: The Init Method

Init Method in Swift:

We gave our instances’ properties default values in the previous exercise. If we know our struct 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:

struct structName {
  var property: Type ;
  init (property: Type) {
     self.property = property ;
  }
} ;

Because methods are essentially functions specific to a type (in this case, a structure), the syntax is similar to that of functions. The init() method is unique in that it does not require the func keyword and is invoked when an instance is created. Methods, like functions, can have parameters but don’t have to. 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:

struct Car {
  var name : String; 
  var speed : Int ;
 
  init (name : String, speed : Int) {
    self.name = name ;
    self.speed = speed ;
  }
};
 
// Using the init() method:
var racingCar = Car(name : "BMW i8", speed : 340) ;
print(racingCar.name) ;   // Prints: BMW i8
print(racingCar.speed) ;// Prints: 340

We set parameters for Car‘s properties in the init() method of Car. We give self.name and self.speed their respective values inside the method. When we create racingCar, a Car instance, we must pass the arguments needed to assign values to racingCar‘s properties into the parentheses. We know that the properties of racingCar were correctly assigned because of our print() statements.

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: