Search code examples
swiftenumsprotocolsextension-methods

Swift: calling default implementation of protocol func from custom implementation


I think the title and the example say it all :) Is it even possible?

protocol Foo {
  func bar()
}

extension Foo {
  func bar() {
     print("bar form extension")
  }
}

enum Day: Foo {
  case sunday, monday

  func bar() {
    switch self {
       case .sunday: print("bar custom implementation")
       case .monday: // I want to call the default implementation
    }
  }
}

Solution

  • Simply remove the declaration from the protocol and only have the extension definition. Then, the compiler will only use the extension method if the concrete type doesn't have an override or if it doesn't know anything about the concrete type except that it conforms to Foo

    protocol Foo {
       // Declaration was deleted
    }
    
    extension Foo {
      func bar() {
         print("bar form extension")
      }
    }
    
    enum Day: Foo {
      case sunday, monday
    
      func bar() {
        switch self {
           case .sunday: print("bar custom implementation")
           case .monday: (self as Foo).bar()
        }
      }
    }
    
    Day.sunday.bar() // prints "bar custom implementation"
    Day.monday.bar() // prints "bar form extension"
    
    

    You need (self as Foo) to make the compiler forget that self is a Day and fall back on the Foo extension function.