In Swift, you can define protocol extensions to provide default implementations for the methods and properties defined in a protocol. This feature enhances flexibility and code reuse by allowing types conforming to the protocol to leverage these default behaviors while also enabling them to override when necessary.
protocol Drawable {
func draw()
}
extension Drawable {
func draw() {
print("Drawing a default shape.")
}
}
struct Circle: Drawable {
func draw() {
print("Drawing a Circle.")
}
}
struct Square: Drawable {} // Uses default implementation
let myCircle = Circle()
myCircle.draw() // Outputs: Drawing a Circle.
let mySquare = Square()
mySquare.draw() // Outputs: Drawing a default shape.
In this example, we define a protocol called Drawable
with a method draw()
. We then provide a default implementation of draw()
in a protocol extension. The Circle
struct provides its own implementation, while the Square
struct uses the default.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?