Swift protocols can provide standard implementations of functions and computed properties by adding extensions to them. I have done this many times. I understand that the default implementation is only used as a “fallback” one . It is executed when the type conforms to the protocol but does not provide its own implementation.
At least as I read the Quick Programming Guide :
If the corresponding type provides its own implementation of the required method or property, this implementation will be used instead of the one provided by the extension.
Now I am faced with a situation where my user type, which implements a specific protocol, provides an implementation for a specific function, but does not execute - instead, the implementation defined in the protocol extension is executed.
As an example, I define a protocol Movablethat has a function move(to:)and an extension that provides a default implementation for this function:
protocol Movable {
func move(to point: CGPoint)
}
extension Movable {
func move(to point: CGPoint = CGPoint(x: 0, y: 0)) {
print("Moving to origin: \(point)")
}
}
Next, I define a class Carthat matches Movable, but provides its own implementation for the function move(to:):
class Car: Movable {
func move(to point: CGPoint = CGPoint(x: 0, y: 0)) {
print("Moving to point: \(point)")
}
}
Now I create a new one Carand omit it as Movable:
let castedCar = Car() as Movable
Depending on whether I pass a value for an optional parameter point, I observe two different behaviors:
move() , Car
→ Movable :
castedCar.move()
:
: (0.0, 0.0)
?