Swift: Memberwise Initialization

Memberwise Initializater in Swift:

We explicitly provided an init() method inside our struct in the previous exercise. In addition, structures have a built-in memberwise initializer in Swift that can be used to assign values to instances when they are created. So, in some cases, we don’t even need to call init()!

Let’s take a look at our code again after removing the init() method from Car:

struct Car {
  var name : String; 
  var speed : Int ;
};

We can make another instance by using the memberwise initializer:

var racingCar = Car(name : "BMW X5", speed : 340) ;

We didn’t need to use the init() method to provide initial values, but we still had to provide arguments for all of them! It’s still critical that the arguments are passed in in the same order as the properties in the Car structure.

While it’s more difficult for other developers to understand what our code means without an init() method (lower readability), we now have a simple way to create instances. Another advantage is that it’s fantastic if we don’t have to.

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: