Struct vs Class in Swift

If you look at structs and classes in Swift, they seem similar, but the most fundamental difference between them is how they handle values passed to them.

In general Struct is pass by value, whereas Class is pass by reference. I will explain the difference by showing an example.

struct Hello {
	var name: String = ""
	var rollno: Int = 0
	init() {
		print("hello init struct")
	}
}

var h1 = Hello()
h1.name = "redflower struct"
print(h1)
var h2 = h1
h2.name = "redflower2 struct"
print(h2)
print(h1)

In the above code, I have declared a variable h1.
var h1 = hello()

In the next line, I assign h1 to h2 and set a different name.
var h2 = h1
h2.name = "redflower2 struct"


If you print the values of h1 and h2, you will see that, they print out different names.
hello(name: "redflower struct", rollno: 0)
hello(name: "redflower2 struct", rollno: 0)
hello(name: "redflower struct", rollno: 0)


This is because, Hello is a structure, a copy of the existing instance is made, and this new copy is assigned to h1. Even though h1 and h2 are made from the same instance, they are two completely different instances behind the scenes.

Moving on to the next example, let’s see how class instances behave.

class HelloClass {
	var name: String = ""
	var rollno: Int = 0
	init() {
		print("hello class init")
	}
	deinit {
		print("hello class deinit")
	}
}

var h1c = HelloClass()
h1c.name = "redflower class"
print(h1c.name) // prints redflower class
var h2c = h1c
h2c.name = "redflower2 class"
print(h2c.name) // prints redflower2 class
print(h1c.name) // prints redflower2 class

If you notice both the variables h1c and h2c print the same value for the name class. Because classes are reference types, h1c and h2c actually both refer to the same HelloClass instance. Effectively, they are just two different names for the same single instance, as shown in the code sample above.

Inheritance is possible with Classes. You can’t do inheritance with Struct.

class BaseHelloClass {
	init() {
		print("base class")
	}
}
class HelloClass : BaseHelloClass {
	var name: String = ""
	var rollno: Int = 0
	override init() {
		print("hello class init")
	}
	deinit {
		print("hello class deinit")
	}
}

Both Structs and Classes can conform to protocol as shown below:

protocol Wish {
	func sayHello()
}
struct Hello : Wish {
	var name: String = ""
	var rollno: Int = 0
	init() {
		print("hello init struct")
	}
	func sayHello() {
		print("sayhello")
	}
}

With respect to memory, struct is stored on a stack(all value types will be here) and class is stored on the heap (all reference types will be here)

Leave a Reply

Your email address will not be published. Required fields are marked *