What is the difference between class and structure in Swift?


This guide will cover what classes and functions there are in the Swift programming language. Also, what are the differences between them?

Most of the time, when we write code in a project, we have to deal with classes and structures. It is true that these two features are the most significant in Swift. In a real−time application, whatever you want to write, you need to create a class to assign responsibility.

If we already have a class option, we need to understand why and when we should use the structure.

Structures are one of the fundamental concepts in the Swift language and they can help to make your code more reusable, flexible, and less tightly coupled. Additionally, they help you improve your skills as an app developer. In what way? Let's check it out.

First, we should understand what are the common features of classes and structures −

We can store information in the form of properties (variables and constants) in both.

  • Both can define functions to perform some tasks.

  • Both can be implemented according to protocols.

  • We can create extensions for both.

  • We can define the initializers to set up the properties.

Capabilities that classes have but structures don't

  • You can make subclasses by inheriting superclasses.

  • You can perform the deinit() action on classes. It means classes can be de-initialized.

  • Classes are reference types.

When should we use structures?

Structures in Swift are useful in a wide range of situations. These are the below −

  • Simple Data Type

    If you don't need to build complex relationships between objects, you should use structs. It means that, when you have to pass objects around in code with no dependencies, it's simpler to use a struct.

  • Don't Need Inheritance

    We know that structures do not support inheritance. Based on that you have a simple scenario in which you should use a struct in your code. Obviously, when you don't need inheritance, it's simpler to use a struct.

  • Thread Safety

    Many things run on different threads in the code. When instances are shared and accessible from multiple threads, it's possible to have deadlock or race conditions. In this case, the structures are thread-safe.

  • Mostly Structured Scenario

    The purpose of creating a class or structure is to store information and perform actions. We mostly need information about value types such as String, Int, Boolean, etc. Obviously, structures are most suitable in this scenario.

When should we use classes?

We know classes have a few essential characteristics that structures don't have −

  • Classes can inherit from another class, which you can’t do with structs. With classes, you can write the class MyViewController − UIViewController to create a subclass of UIViewController. Structs can implement protocols, can be extended, and can work with generics, though!

  • Classes can be deinitialized, i.e. they can implement a deinit function. Also, you can make one or more references to the same class (i.e., classes are a reference type).

  • Classes come with the built-in notion of identity because they’re reference types. With the identity operator === you can check if two references (variables, constants, properties, etc.) refer to the same object.

  • Use classes if you want to interop between Swift and Objective−C. If you need Objective−C interoperability, you’ll need to use classes. For example, if you want to use @objc and dynamic in a Realm data model, that model needs to be a class.

Let's understand the difference between Class and Structure by example −

Example

class StudentClass {
   var name: String
   var grade: Int
   init(name: String, grade: Int) {
      self.name = name
      self.grade = grade
   }
}
let student1 = StudentClass(name: "Ramesh Chandra", grade: 9)
let student2 = student1
student2.name = "Ramesh Kant"
print("student1 name: \(student1.name)")
print("student2 name: \(student2.name)")

struct StudentStruct {
   var name: String
   var grade: Int
}
let student3 = StudentStruct(name: "Anish Sharma", grade: 8)
var student4 = student3
student4.name = "Anish Gupta"
print("student3 name: \(student3.name)")
print("student4 name: \(student4.name)")

Output

student1 name: Ramesh Kant
student2 name: Ramesh Kant
student3 name: Anish Sharma
student4 name: Anish Gupta

Explanation

In the above example, we have created a class called StudentClass and a structure called StudentStruct. Now you have to understand the following points −

  • Initializers are provided by default in structures, while we need to define them for classes.

  • The instances (student1 and student2) are constant and do not need to be variable even if the properties are changed.

  • For structure, we make student3 a constant since no properties need to be changed. However, another object called student4 is a variable as we have to make changes to properties.

  • In last, you can see the output. It is clear that class objects are sharing the memory location, which is why another instance of the class is able to reflect the change.

The difference in Class and Structure

Summarize the difference between Class and Structure

Comparision Class Structure
Type Classes are reference types. Structures are value types.
Inheritance Classes have an inheritance that allows one class to inherit the characteristics of another. Structures do not support inheritance.
Storage Class instances are stored on the heap. Structure properties are stored on the stack.
Initializer We have to define the initializer manually. Struct gets a default initializer automatically.
Thread−safe Classes are not fully threadsafe. The structure is threadsafe or singleton at all times.

Conclusion

You learned when to use classes and structures. Based on that, you can decide which one you are intending to use.

Inheritance is the most significant difference between a class and a structure. With classes, you can clearly define a parent−child connection between subclass and superclass.

When you follow the struct−default approach, you keep the option to upgrade to a class later on.

Updated on: 09-Dec-2022

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements