Introduction

In this article, we will learn how to implement the classes in Swift programming language. Class is the basic concept of Object Oriented Programming.

What are Classes?

Creating Classes

The structure and declaration of class is also the same in swift programming language. Now I am discussing the basic example of class -- now consider the following code,

code

Now I declare a simple class in which I declare two variable names as first name and last name and make a function which shows the full name but when I run it you see an error that “Class Employee has no initializers,” now the points in my definition of class will clear up your concept more.

Creating Classes with Initializers

In Swift programming language, we initialize our class with a different approach -- we have a built-in method in swift called “init” which performs the action called initialization.

Now we modified our previous code and checked with initializer that our code runs correctly.

code

Class is a Reference Type

Class Uses Heap Memory

Class Adopt Protocol

If you learn the concept of Protocol in swift programming language, the best advantage of protocol is that we inherit and adopt the protocol. Now I am again giving you an example which will clear up your concept about adoption of protocols.

code

In this Code example, I justify my point which I gave when I gave you a definition of class. Here you see that class adopts the protocol and we modified our example with protocol method which clears up your concept more.

DE initialization Class

Now we see how we DE initialization in the class means we assign at nil. In Swift programming language we have some built-in methods like “deinit” to DE initialization the class. Now I am discussing the example which will clear up your concept of DE initialization of classes.

code

In this example, we first declare two variables with name “firstname” and “lastname” and then we initialize both variables using “init” method and then immediately we use “deinit”.

Then outside the class we create nil instance the “?” in class which means we assign it “nil;” then I assigned two values and immediately assiged it “nil;” now after assigning “nil” our class is DE initialized.

Conclusion

This is all about classes in swift programming, I am guesing that you have now a clear picture about the classes, but if you have any confusion you can ask me I will try to clear up your concept.