Introduction
In this article, we are comparing the structure and classes in Swift language and I will try to make you understand the difference between the structures and class, and the following chart enables you to understand the concept about the structure and class.
Comparing Structures and Classes in Swift
Key Point of Structure
- Implicit copying of the values.
- Data is immutable.
- Useful for representing the values.
- Fast memory allocation (stack).
- It provides you the member wise declaration.
Member Wise Declaration
If we declare struct keyword, you can see that at the bottom, we make an object of struct. We have two suggestions -- one is simple, the declaration, and another is the member wise declaration. This declaration can be only held in struct.
Structure is a Value Type and Classes Are Reference Type, Is There Any Difference Between Coding and Result?
Structure
Yes, there are many differences between the coding and a result, I am discussing an example here, which helps to explain to you the concept clearly.
Code
-
- func changeValue(var number: Int) - > Int
- {
- number += 1000
- return number
- }
-
- var myNumber = 99
-
- changeValue(myNumber)
-
- myNumber
Listen: First, we simply declare a function with the number 1000, followed by declaring a new variable and assigning it any number. I pass this variable into my function. You will see that my previous number is added in the function and see the sum result, but when I print the myNumber variable again, the value of it doesn’t change and remains the same.
Key Point of Classes
- Implicit sharing of the objects
- Data is immutable
- Useful for representing the things
- Slower memory allocation (heap)
- Classes store the properties and methods
- Classes are the references, that are shared on assignment.
Classes
Now, I will discuss the example code of the class, which is exactly the opposite of the structure.
In this example, we will declare the class name as checking and then we declare a variable. Assign a number and then we make a function. We make an instance of the class, which is passed to our function and then we print the instance. Now, you will see that the value changes, using the class reference.
Code
-
- class checking
- {
- var value: Int = 99
- }
- func ChangedObject(var object: checking) - > Int
- {
- object.value += 1000
- return object.value
- }
-
- var myObject = checking()
-
- ChangedObject(myObject)
-
- myObject.value
Instance Declaration If we make an instance of the class, we don’t have an option to declare a class as a member wise declaration. Here, you can see that we need to change the keyword struct to the class and the member wise declaration can’t appear, because the class gives this permission
Conclusion
In this article, I tried to explain the concept of struct and class. I also gave the conceptual difference between these two things, because the beginner developers and students confuse these two things.