Protocols and Extensions
Protocols and extensions are powerful features in Swift that allow you to define blueprints for what a type should do and extend the functionality of existing types, respectively. This section will introduce you to the concepts of protocols and extensions, how to define them, and how to use them in your Swift projects.
What are Protocols?
Protocols define a blueprint of methods, properties, and other requirements for a particular task or functionality. They don't provide implementations for these methods; they only describe what methods a conforming type must have.
Declaring Protocols
You can declare a protocol using the protocol
keyword.
protocol Drawable {
var color: String { get set }
func draw()
}
Conforming to Protocols
A type can conform to a protocol by implementing all its requirements.
struct Square: Drawable {
var color: String
func draw() {
print("Drawing a square in \(color) color.")
}
}
What are Extensions?
Extensions add new functionality to an existing class, structure, enumeration, or protocol type. They are useful for adding methods or computed properties to types for which you don't have access to the original source code.
Declaring Extensions
You can declare an extension using the extension
keyword.
extension Double {
var squared: Double {
return self * self
}
}
Using Extensions
Once an extension is defined, the new functionality is available on all instances of the type.
let number = 5.0
print(number.squared) // Output: 25.0
Combining Protocols and Extensions
You can use extensions to provide default implementations for protocol methods, effectively allowing you to extend protocols.
extension Drawable {
var color: String {
get { return "black" }
set {}
}
func draw() {
print("Drawing in \(color) color.")
}
}
Now, any type conforming to Drawable
but not providing its own draw
method will use the default implementation.
Conclusion
Protocols and extensions are essential tools in Swift for defining blueprints and extending functionalities. Protocols allow you to define what a type should do, while extensions let you add new functionalities to existing types. Together, they offer a flexible way to write clean, reusable, and organized code in Swift.
Book a conversation with us for personalize training today!