DEV Community

Ajithmadhan
Ajithmadhan

Posted on

Class vs Struct in Swift

Class and struct are general-purpose of a template to defines bellow characteristics.

  • Property
  • Method/functions
  • Initializers
  • Protocol
  • Extension

Class and struct looks similar except the keyword used to define.
eg:

struct A{
var name = "Ajith"
var age = 10
var run(){...}
}
Enter fullscreen mode Exit fullscreen mode
class B {
var name = "Ajith"
var age = 10
var run(){...}
}
Enter fullscreen mode Exit fullscreen mode

What is common in both?

  • Both has property,methods,Initializers,Protocol,Extension
  • Provides Subscripts to access their values
  • failable init can be used in both
  • Properties and method in both are accessed using .(dot) syntax.

Things Available Only in Class:

  • deinit can be used only with class.
  • Classes can inherit the characteristics of another class. Struct can’t inherit from other struct.
  • Reference counting allows more than one references.
  • Type of class instance can be checked at runtime.

Things Available Only in Struct:

  • Struct has default member wise initializer. For class we need to define explicitly.
  • Struct have the benefit of mutation safety that behind its hood no other thing can mutate its value which may prone to many bugs that are hard to debug.

Difference between struct and class:

  • Class uses keyword "class" and Struct uses keyword "struct" .
  • For modifying the self property in struct from a function you need to define mutating at the beginning of function. Class doesn’t required anything.
  • One of the most difference is value vs reference type.
  • If you create struct instance with let property, you can’t modify its properties. If you create a class instance with let property, you can modify its properties.

Value vs reference types:

  • Classes are reference type : which means reference to a location in the memory where class instance is stored.
  • Struct and enumeration are value type: which means each reference has it’s own copy of data
  • If you share/assign instance of class to different references, all these references will have a single shared data. That means any changes in that class instance will be available to every reference
  • If you share/assign instance of struct to different references, every reference will creates its own memory to store the data. Any changes in struct in one reference will not affect in other reference.
  • Memory allocation for both class and struct is different. Because of this difference, class and struct behaves differently while sharing its instances.

Value types are stored in stack memory and reference type are stored in heap memory.

Oldest comments (0)