Struct & Class

Struct and Class are structures that are close to each other, we have to choose what to do according to the situation. Sometimes this is mandatory.

Classes are reference-based and Structs are value-based. In other words, when you create a class, you create a reference type in memory, and since the changes you make in this class change the reference, this change will also appear in all objects that adopt the class. Each strongly referenced object you define to the same class increases the reference number in arc by one, and arc keeps this class in memory and does not release it until this number is not reset—until there is at least one strong link holding the class instance.

for example;

Market Sınıfı
Çıktı

Even if we just change the name of the market object, the name of our superMarket object based on the same item also changes. This reference property gives the class an identity. If we have an identity-based need, it makes more sense to use a class. On the other hand, let’s try to do the same with the struct.

Market Struct
Çıktı

As you can see, we got two separate outputs from two separate objects, since they are not reference-based. This is because Structs are value based . They do not refer to the same item.

As with Classes, Structs support initialize but cannot run deinit, this is class specific. Classes support inheritance, Structs do not support inheritance, but both structures support protocols, but the protocol should not be Objective-C based, because Structs do not work with Objective -C (outside the protocol). Only classes can do this.

for example;

When we try to add NSFileProviderItemProtocol to the Struct structure, we get such an error, but when we do the same in Class, we will not encounter an error as long as we provide the features required by the protocol.

If your struct needs copying, identity, Objective -C or inheritance use Class otherwise don’t give up on Structs. Since structs are value-based, it provides great convenience when debugging, because there is nothing to change that structure from anywhere else. We do not need to think about the whole project, it reduces the problem to a narrow area, making it easier for us to catch the error. This feature makes the environment safer, but if you are using a Class, it is a reference type, so activities for the same reference may cause a deadlock. Another advantage of using a struct is that it provides the ability to switch to a class structure whenever you want. That’s why Apple recommends starting with Struct by default. If you need to convert that structure to a Class while using a struct, you just need to drop the struct keyword and simple struct prefixes (mutating).

Yayım tarihi
Swift olarak sınıflandırılmış , ile etiketlenmiş

Yorum Gönderin

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir