Difference between Struct, Class and Protocol in Swift

Krishan Shamod
2 min readMay 25, 2022

Hi guys, today I’m going to talk about the difference between struct, class and protocol in Swift. Before going further Swift is a powerful and intuitive programming language for developing iOS, iPadOS, macOS, tvOS, and watchOS applications.

There are two choices when we need to decide how to store data and model behaviour: Classes and Structs. Let’s see them one by one.

Class

Classes are building blocks of flexible constructs. Similar to constants, variables and functions the user can define class properties and methods.

Also classes are reference types. When a reference type is assigned to a variable or constant, or supplied to a function, it is not copied. A reference to the same existing instance is utilized instead of a copy.

class classname {
Definition 1
Definition 2
..........
Definition n
}

Struct

Structs are complex data types, meaning that they are made up of multiple values. You then create an instance of the struct and fill in its values, then you can pass it around as a single value in your code.

Why we need structures?

  • To encapsulate simple data values.
  • To copy the encapsulated data and its associated properties by ‘values’ rather than by ‘references’.
struct Person {
var clothes: String
var shoes: String
}

Protocol

A protocol in Swift defines a blueprint of methods or attributes that can be adopted by classes. It’s like a interface in other languages.

protocol Animal {

// blueprint of a property
var name: String { get }


// blueprint of a method
func eat()
}

Other classes must follow the protocol in order to use it. We must give a real implementation of the method when we conform a class to the protocol.

// conform class to Animal protocol
class Dog: Animal {

// implementation of property
var name = "Tommy"

// implementation of method
func eat() {
print("Eating!")
}
}

So, those are the differences between Struct, Class and Protocol in Swift.

--

--