Structures & Classes in Swift

When designing a code snippet of a system, we had data types such as Array Tuple, Dictionary, and Sets to hold multiple values ​​simultaneously. But we need to standardize this as much as possible. So always using class and struct can make things easy. We abstract the objects and pass them to the code by defining classes and structs. These types of structures are considered a philosophy on the part of the software. For example, imagine that you are making a grocery order application, and there will be screens with different features between the shopping user and the user who is selling the products.

It wouldn’t be wrong to say that everything around us is the product of a standard. Looking around, we can see that everything we see is an object.

Objects are embodiments of classes. Objects have states and behaviours.

What are Class and Struct?

Let’s think about the design of a machine, where engineers make construction, strength, and aerodynamic designs. Some drawings and calculations are made. If we believe that this is a car, the features that the user needs here will be to start the car, drive, and stop.

Here, in the background, the car’s properties will be defined as state and behaviour in the class. In contrast, state properties create conditions such as the car’s colour, fuel tank capacity, amount of torque, and fuel type, In the behaviour features, step by step, what methods will be performed when the gas, clutch, and brake pedals are pressed.

The car accelerates when the accelerator pedal is pressed. When the gas pedal is pressed, the gas pedal pushes air into the intake manifold depending on the throttle, and the air volume changes according to the opening rate of the throttle. The more air enters the engine, the greater the speed and power of the motor. But we don’t need to know these; I stepped on the gas and accelerated. That’s enough to know. Methods hide complex operations from the user, allowing only the function to be called. It is a great simplicity for the user.

If we make an example, it seems as if everything will become more apparent;

  class Car {
      var color:String?
      var tork:Int?
      var fuelTank:Int?
      var transsmissionType:String?
      var fuelType:String?
      var active:Bool?

      init() {
          print("empty constructor")
      }
  }

As you can see, while specifying the class type in the example, what must set the category name given to the class here. Here, the name of the Car class must start with a capital letter; that is, it must be in UpperCase format. Also, we have created an empty constructor by defining init(). Then you can determine the variables and assign any value or specify the value type by creating an empty structure as I did above.

Our data types, such as array, tuple, dictionary, and sets, which hold more than one variable simultaneously, could already have more than one value. But our goal with classes and structs is to aggregate multiple variables, structs, and functions. In such a case, we want to do all these operations under a variable or a data type. One of the data types that we can do this operation is struct.

Let’s do this with an example:

    struct Car {
        var color:String?
        var tork:Int?
        var fuelTank:Int?
        var transsmissionType:String?
        var fuelType:String?
        var active:Bool?
    }

Like Classes, Structures are UpperCase type Car starts with a capital letter, and variable types can be assigned.
Struct is an interface for creating objects (or instances) in Swift. A struct can be thought of as a factory. A car brand produces different models of cars, and these cars come under one roof.
You can get the apartment block by putting the flats on each other. Each flat has the same structure as before flat. But what can change after?

Structs and Classes Diffrences

Although both methods have similar features, there are some differences.

1. Initialization

Structs give you a free init while you need to define for class. In the above example, we created an empty initialization to avoid getting an error from Xcode. Let’s create a full constructor.

  class Car {
      var color:String?
      var tork:Int?
      var fuelTank:Int?
      var transsmissionType:String?
      var fuelType:String?
      var active:Bool?

      init(color:String,tork:Int,fuelTank:Int,transsmissionType:String,fuelType:String,active:Bool) {
            self.color = color
            self.tork = tork
            self.fuelTank = fuelTank
            self.transsmissionType = transsmissionType
            self.fuelType = fuelType
            self.active = active
      }
  }

2. Inheritance

Classes support inheritance, while structs don’t.

A class can inherit methods, properties, and other properties from another class. When a class inherits from another class, the inheriting class becomes a subclass, and the class it inherits becomes its superclass. Inheritance is a feature that distinguishes Swift from other languages.

The example below defines a base class called Movie. This base represents a stored property called duration(property type of Int), with a description.

 class Movie {
    var duration = 0
    var description: String {
        return "The duration of the movie is \(duration) minutes"
          }
  }

Let's create a new instance of Movie with initializer syntax, which writes which is written as a type name followed by empty parentheses:

   let someMovie = Movie()

After a new movie is created, you can access the annotation feature again.

print("Movie: \(someMovie.description)")

Subclassing is the act of basing a new class on an existing class. The subclass inherits characteristics from the current class, which you can refine. You can also add unique attributes to the subclass.

To indicate that a subclass has a superclass, write the subclass name before the superclass name, separated by a colon:

 class SomeSubclass : SomeSuperclass {
     // subclass definition here
 }

The following example defines a subclass called Drama, with a superclass of Movie:

 class Drama:Movie {
   var effectType = "Nervous"
  }

3. Classes are reference types, while structs are value types.

Reference type:

Here you go. Now let’s look at the code block we identified in our first example. Here, we have determined the colour characteristics for the audi_A5 brand vehicle and assigned the color black. We have selected and set the features for the hyundai_i20 vehicle. Here we have posted black color for audi_A5. Then we determined the components for a second brand, Hyundai, and this time we said that the colour of hyundai_i20 is Grey. Right here, because the class type is a reference type, the color of the Audi automatically changed and became grey.

    let audi_A5 = Car(color: "Black", tork: 1750, fuelTank: 54, transsmissionType: "Automatic", fuelType: "Diesel", active: true)
    audi_A5.color = "Black"

        var hyundai_i20 = audi_A5
        hyundai_i20.color = "Gray"
        print(audi_A5.color!)

When the print command is typed, the colour of the Audi brand vehicle, which is black, turns grey.

Value Type:

Value type is also used for structs, where when a new struct value is passed to an old struct, copying takes place and a new memory is allocated.

When the print command is entered, the colour of the Hyundai brand vehicle will be changed to grey, but the Audi brand vehicle will not be affected by this situation.

    let audi_A5 = Car(color: "Black", tork: 1750, fuelTank: 54, transsmissionType: "Automatic", fuelType: "Diesel", active: true)
    audi_A5.color = "Black"

        var hyundai_i20 = audi_A5
        hyundai_i20.color = "Gray"
        print(audi_A5.color!)

The topic is long, but I think it is necessary to summarize and say goodbye:
It’s pretty hard to define and remember multiple variables repeatedly. There will be a variable crowd. Variable names will be confused. It will also be an excessive length of code. That’s why Struct and Class topics are essential and used a lot.
This article focused on classes, structures, and the differences between these methods.

I hope it was helpful.

Please write to me with your questions and feedback.

Follow my way!

LinkedIn | Twitter | Github


Other sources

developer.apple.com/documentation/swift/cho..

docs.swift.org/swift-book/LanguageGuide/Cla..