What is the difference between protocols and classes when it comes to abstract classes?
sobes.tech AI
Answer from AI
A protocol defines a contract — a set of requirements (methods, properties, initializers) that a type conforming to the protocol must implement. Protocols do not provide implementations for most of their requirements. Protocol instances cannot be created.
An abstract class in languages other than Swift (e.g., Java) is a class that cannot be instantiated directly. It contains both implemented methods (or properties) and abstract methods that must be implemented in its subclasses.
In Swift, there is no concept of abstract classes in the traditional sense. The functionality of abstract classes in Swift is achieved through a combination of protocols and classes.
Using a protocol, you can define an interface, and then create a regular class that conforms to this protocol and provides an implementation. Partial implementation of a protocol can be provided via protocol extensions, but this does not make the protocol an "abstract class" in the pure sense.
| Protocol (Swift) | Abstract class (traditional) | |
|---|---|---|
| Purpose | Defines a contract (interface) | Defines common behavior and structure with the possibility of partial implementation |
| Implementation | Usually contains no implementation (except extensions) | Can contain both implemented and abstract methods |
| Instantiation | Cannot create an instance of the protocol | Cannot instantiate an abstract class directly |
| Inheritance | Conformance to protocol | Inheritance (inheritance) |
| Multiple adherence | A type can conform to multiple protocols | A class can inherit from only one class (in most languages) |
| In Swift | Is the primary form of abstraction | No direct equivalent, emulated with protocols and classes |
Example of emulating an abstract class using a protocol and a class in Swift:
Protocol defining abstract requirements:
// Protocol as a contract
protocol Drawable {
func draw()
var color: String { get set }
}
Class conforming to the protocol and providing implementations:
// Class implementing the protocol
class Circle: Drawable {
var color: String
init(color: String) {
self.color = color
}
func draw() {
print("Drawing a circle of color \(color)")
}
}
Extension providing default partial implementation:
// Extension providing default implementation (does not make the protocol an abstract class)
extension Drawable {
func draw() {
print("Starting to draw something of color \(color)")
}
}
Thus, in Swift, protocols play a key role in achieving polymorphism and abstraction, replacing the concept of abstract classes from other languages.