Swift Language: Struct Vs Class Vs Protocol
Structures and classes are the building blocks of flexible constructs, that helps developers to decide the way of storing data and modeling behavior in their programs. on the other hand, Protocols define blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality., then let it be adopted by a class or a structure provide an actual implementation of those requirements.
Class
Class can be termed as a technique used to define and store properties and methods. The “class” keyword is used to create a class in Swift. For example,
class ClassName {
// class definition
}
Classes are reference types. Reference types are not copied when they’re assigned to a variable or constant or when they’re passed to a function. Rather than a copy, a reference to the same existing instance is used. For example,
Struct
Struct also can be termed as a technique used to define and store properties and methods. The “struct” keyword is used to create a struct in Swift. For example,
strcut StructName {
// struct definition
}
Structures are value types. It is copied when it’s assigned to a variable or constant, or it’s passed to a function. For example,
Protocol
Protocol:
- Is a blueprint that a class or struct follows
- Is a communication contract for unrelated objects to rely on
- Defines methods and values
To put it simply, protocols represent interfaces like many other languages do. For example,
Similarities in a class, struct and a protocol
Classes and structs’ shared features that can often be used interchangeably in Swift. However, protocols when considered alone from class and struct carry orthogonal concepts. Protocols and classes, structs become fairly similar, but they are never the same. Therefore, only several similarities between classes and structures are mentioned here as follows,
· Can define properties to store values
· Can define methods to provide functionality
· Can define subscripts to provide access to their values using subscript syntax
· Can be extended to expand their functionality beyond a default implementation
· Can conform to protocols to provide standard functionality of a certain kind
However, even classes and structs have differences and uniqueness, that brings the flexibility to developers to use them where they deem best.
When designing a type, we have to think about whether ownership of a particular instance of this type “has to be shared among different parts of our program, or if multiple instances can be used interchangeably as long as they represent the same value. To share ownership of a particular instance, we have to use a class. Otherwise, we can use a struct.
Chris Eidhof. “Advanced Swift.”
Differences between a class, struct and a protocol