Implementing a function with a default parameter defined in a protocol

Swift protocols can provide default implementations for functions and computed properties by adding extensions to them. I’ve done that plenty of times. It is my understanding that the default implementation is only used as a “fallback”: It’s executed when a type conforms to the protocol but doesn’t provide its own implementation.

At least that’s how I read The Swift Programming Language guide:

  • What does “Protocol … can only be used as a generic constraint because it has Self or associated type requirements” mean?
  • Pass data between ViewController and ContainerViewController
  • What is the in-practice difference between generic and protocol-typed function parameters?
  • All Classes Conforming to Protocol Inherit Default Implementation
  • Swift: Failed to assign value to a property of protocol?
  • Why can we not cast to protocol types with associated types but achieve the same effect using generics?
  • If a conforming type provides its own implementation of a required method or property, that implementation will be used instead of the one provided by the extension.

    Now I ran into a situation where my custom type that implements a certain protocol does provide an implementation for a particular function but it’s not executed — the implementation defined in the protocol extension is executed instead.


    As an example, I define a protocol Movable that 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 Car class that conforms to Movable but provides its own implementation for the move(to:) function:

    class Car: Movable {
    
        func move(to point: CGPoint = CGPoint(x: 0, y: 0)) {
            print("Moving to point: \(point)")
        }
    
    }
    

    Now I create a new Car and downcast it as a Movable:

    let castedCar = Car() as Movable
    

    Depending on whether I pass a value for the optional parameter point I observe two distinct behaviors:


    1. When passing a point for the optional parameter

      the Car‘s implementation is called:

      castedCar.move(to: CGPoint(x: 20, y: 10)) 
      

      Output:

      Moving to point: (20.0, 10.0)


    1. When I invoke the move() function without providing a value for the optional parameter the Car‘s implementation is ignored and

      the Movable protocol’s default implementation is called instead:

      castedCar.move()
      

      Output:

      Moving to origin: (0.0, 0.0)


    Why?

    Solutions Collect From Internet About “Implementing a function with a default parameter defined in a protocol”

    This is simply due to the fact that the call

    castedCar.move(to: CGPoint(x: 20, y: 10))
    

    is able to be resolved to the protocol requirement func move(to point: CGPoint) – therefore the call will be dynamically dispatched to via the protocol witness table (the method by which protocol-typed instances achieve polymorphism), allowing Car‘s implementation to be called.

    However, the call

    castedCar.move()
    

    does not match the protocol requirement func move(to point: CGPoint). It therefore won’t be dispatched to via the protocol witness table (which only contains method entries for protocol requirements). Instead, as castedCar is typed as Movable, the compiler will have to rely on static dispatch. Therefore the implementation in the protocol extension will be called.

    Default parameter values are merely a static feature of functions – only a single overload of the function will actually be emitted by the compiler (one with all the parameters).

    Attempting to apply the function by excluding one of its parameters which has a default value will simply trigger the compiler to insert an evaluation of that default parameter value (as it may not be constant), and then insert that value into the call.

    For that reason, functions with default parameter values simply do not play well with dynamic dispatch. You can also get unexpected results with classes overriding methods with default parameter values – see for example this bug report.


    One way to get the dynamic dispatch you want for the default parameter value would be to simply define a static property requirement in your protocol, along with a move() overload in a protocol extension which simply applies move(to:) with it.

    protocol Moveable {
        static var defaultMoveToPoint: CGPoint { get }
        func move(to point: CGPoint)
    }
    
    extension Moveable {
    
        static var defaultMoveToPoint: CGPoint {
            return .zero
        }
    
        // simply apply move(to:) with our given defined default.
        // as defaultMoveToPoint is a protocol requirement, 
        // it can be dynamically dispatched to.
        func move() {
            move(to: type(of: self).defaultMoveToPoint)
        }
    
        func move(to point: CGPoint) {
            print("Moving to origin: \(point)")
        }
    }
    
    class Car: Moveable {
    
        static let defaultMoveToPoint = CGPoint(x: 1, y: 2)
    
        func move(to point: CGPoint) {
            print("Moving to point: \(point)")
        }
    
    }
    
    let castedCar: Moveable = Car()
    castedCar.move(to: CGPoint(x: 20, y: 10)) // Moving to point: (20.0, 10.0)
    castedCar.move() // Moving to point: (1.0, 2.0)
    

    Because defaultMoveToPoint is now a protocol requirement – it can be dynamically dispatched to, thus giving you your desired behaviour.

    As an addendum, note that we’re calling defaultMoveToPoint on type(of: self) rather than Self. This will give us the dynamic metatype value for the instance, rather than the static metatype value of what the method is called on, ensuring defaultMoveToPoint is dispatched correctly. If however, the static type of whatever move() is called on (with the exception of Moveable itself) is sufficient, you can use Self.

    I go into the differences between the dynamic and static metatype values available in protocol extensions in more detail in this Q&A.