Structures and Classes in Swift
What are they and what is the difference between both ?
Let’s be clear that before we get into OOP most of tutorials must explain objects what are they before getting deeper , and that’s what we will explain and then check the syntax of Classes and Structures and some examples .
In Swift, objects are instances of classes or structs that encapsulate data and behavior together. They are fundamental building blocks of object-oriented programming (OOP). Objects allow you to represent real-world entities or abstract concepts as self-contained units, making your code more organized, reusable, and easier to maintain. “ this is what most books says about objects and it’s totally true”
A real life example of objects , basically look around you everything around you is an object , each object has it’s state and behavior’s , for example a dog has state’s such as color , name and type for example , and for behaviors we got barking or fetching , you can imagine other things and relate it to the Dog example , another example is cars , we got many companies which manufacture cars such as Mercedes , BMW and so on , each car has it’s own specifications such as color , model , and even the price is different , i think now you can imagine in a better way .
Structs
actually structs or structures and classes are so close to each other but with little difference which we will be discussing in detail later here .
In Swift, structs are value types that allow you to encapsulate related data and behavior together. They are similar to classes but have some key differences. Structs are commonly used to model simple data types or small pieces of data with value semantics.
We’ve mentioned here “ Value type” which is a core difference betwee structs and classes and will be discussed .
here is a code example of a simple struct :
We start by declaring key word “struct” which defines a structure in swift , followed by the structure name “ Rectangle”
Note : Structure names and Classes always starts with a capital letter , what if we have more than one word ?Class names should be nouns, in mixed case with the first letter of each internal word capitalized example : ApplePie .
We defined two variables , height and width which we call properties of the Rectangle of type double , The Rectangle
struct also has a method called area()
, which calculates and returns the area of the rectangle based on its width and height.
To instantiate an object basically we can create a constant or a variable as we can see rectangle1 and rectangle2 are objects of the struct Rectangle , we can see there two arguments which are the width and height , but did we de declare any in parameters like we do in functions for example , all structs come with a default initializer. This is called the memberwise initializer. A memberwise initializer assigns each property in the structure to self. This means you do not need to write an implementation for an initializer in your structure , we will understand it more when we declare objects from classes .
Let’s print each value of our objects using the Area function .
alright we’ve assigned two variables each to different rectangle as we can see each rectangle has it own values and doesn't affect the other rectangles , remember this note because it’s related to what we’ve said earlier that structs are value type,meaning they are copied when assigned to a new variable or passed as a function argument. Each copy of a struct is independent and does not share the same underlying memory. This behavior ensures that changes to one struct instance do not affect others , which is a huge benefit of structures if you need that ability of course .
Let’s define classes to see the difference more clearly.
Classes
Directly let’s discuss thought an example , instead of struct we use class keyword to declare classes and the naming is the same in structs , starts with capital letter “ Person” , there’s something different here right ? it’s almost the same syntax as structs but with an init function , what is it ? let’s discuss it .
init
method, which is the initializer or constructor of the class. It allows us to create new instances (objects) of the Person
class with initial property values. When we create a new Person
object, the init
method is called automatically to set the initial values of the name
and age
properties, if you’ve studied another language than swift such as c# or java , constructor is a main thing in classes , you can see this is the default constructor , why did we use this method ? and is it a must ?
Yup it’s a must in classes to declare the ‘ init ‘ method to initialize the properties of our class here , if we try to call the “introduce” method , this is what we get .
To access properties and methods of an object, you use dot notation (object.property
or object.method()
). For example, person1.introduce()
calls the introduce()
method on the person1
object.
we’ve mentioned that structs are ‘value type’ , classes on the other hand are ‘ reference type ‘ , what are the difference ? .
Value type VS Reference Type
Look at both examples and let’s discuss the differences.
first : Structs (Value Types):
- Value Semantics: Structs are value types. When you create a new instance of a struct and assign it to a variable or pass it as an argument to a function, a copy of the entire struct is made, and the new instance is independent of the original. Any modifications to the new instance won’t affect the original one, and vice versa.
- Copies: When you pass a struct to a function, the function receives a copy of the original struct. Any modifications made within the function are made on the copy, not the original.
We know these but we need an example , sure here is it :
We have a simple struct which has two properties: x and y , we’ve two objects as well p1 which has x to the value 10 and y to the value 20 then we assigned p2 to p1 , now p2 is a copy of 1 if we try to print p2 points before changing anything it will be exactly the same as p1 , but now we’ve changed the value of p2.x to 30 instead of 10 , when we tried to print p1.x we got 10 which is the value of it so “ No changes “ now if we print p2.x we’ve got 30 which is the value we’ modified , that is exactly the meaning of Value types .
Secondly : Classes (Reference Types):
- Reference Semantics: Classes are reference types. When you create a new instance of a class and assign it to a variable or pass it as an argument to a function, you are actually creating a reference to the same instance in memory. Both the original variable and the new variable point to the same object in memory.
- Shared Data: Any changes made to the object through one variable are visible through all other variables that refer to the same object.
These are the meanings we know as well , let’s look at a real example :
we have two objects dog1 and dog2 , we’ve assigned the name of dog1 to “Buddy” then assigned dog2 to dog1 , so now dog2 refers to the same object as dog1 , let’s modyfiy dog2 name to Max , does that affect dog1?
Let’s print and checkout the results.
as we can see that dog1 name has been changed “modified” to dog2 name which is Max , because they are sharing the same memory now , we won’t get in memory details but that’s a main difference between value type and reference type , difference between structs and classes .
In summary:
Structs (value types) are copied when assigned or passed around.
Classes (reference types) create shared references to the same object in memory when assigned or passed around. Modifying one variable affects all other variables pointing to the same object.
Before we end this , another difference between structs and classes that structs doesn’t support inheritance “ OOP Concept “ , no one is better than another , but it all depends on what you want for your application .
Thank you .