Comparison of Struck, Proto(protocol) & Class in Swift

Nirmal Kapilarathne
2 min readMay 23, 2022

--

Hello Friends…

What is a class in Swift?

Swift classes are the basis of flexible constructs. Constants, variables, and functions can all be defined as class attributes and methods. When declaring classes, Swift can avoid the requirement for users to generate interfaces or implementation files. Swift allows us to define classes in a single file and have external interfaces produced automatically once the classes have been initialized.

Example of a Swift Class

class student {
var name: String
var mark: Int
}

What is a Struct in Swift?

In Swift, a struct is used to store variables of various data kinds. Let’s say we wish to remember a person’s name and age. Two variables can be used to hold information: name and age. Consider the situation where numerous persons require the same information.

Example of a Structure

struct Student { 
var name = String
var age = Int
}

What is a Proto?

Generally, a protocol:

  • Is a blueprint that a class or struct follows
  • Is a communication contract for unrelated objects to rely on
  • Defines methods and values

Example of a Protocol

protocol EmployeeProtocol {
var emplname: String { get }
var description: String { get }
var salary: Int { get set }
func paySalary(salary: Int) -> String
}

Comparison between Class, Struct, and Proto in Swift

1)Class vs Struct:

  • Classes can inherit from another class, as you inherit from UIViewController to create your own view controller subclass, but struct can’t.
  • Classes are reference types and structs are value types.
  • Typecasting enables you to check and interpret the type of a class instance at runtime.
  • In class, a Shared mutable state is required, and in struct, unique copies with an independent state are required.
  • In class, Objective-C interoperability is required and in a struct, the data is used in multiple threads.

2) Proto vs Class:

  • Classes are concrete things. While they might adopt protocols — i.e., say they implement the required properties and methods — they aren’t required to do that.
  • You can create objects from classes, whereas protocols are just typed definitions.
  • Protocols are like abstract definitions, whereas classes and structs are real things you can create.

3) Struct vs Proto:

  • In Swift, protocols provide communication across unrelated objects by defining methods and variables similar to those found in classes, enums, and structs.
  • Protocols are similar to interfaces, and Structs are similar to classes, except they are passed by value from one variable/function to the next.

Thank you very much for reading!

Hope to see you again with the next article. Till then, GOODBYE…!

--

--

Nirmal Kapilarathne
Nirmal Kapilarathne

No responses yet