Search code examples
swiftprotocols

DRY code: how to call an implementation from another protocol


I have some code I want to DRY up, I don't want to repeat/maintain the same code at multiple places.

protocol Programable {
    var log: String { get }
}

protocol Convertable {
    var status: String { get set }
}

extension Programable where Self: NSManagedObject {
    var log: String {
        return <managed object related stuff>
    }
}

extension Programable where Self: NSManagedObject, Self: Convertable {
    var log: String {
        return <managed object related stuff> + status
    }
}

How can I call the first extension's log in the second extension, so I don't have to repeat the details in the code?


Solution

  • It is impossible to call the same overload if only the constraints differ. Instead, move the commonality into something private. There is no naming convention for this.

    extension Programmable where Self: AnyObject {
      var log: String { where_Self_is_AnyObject_log }
      private var where_Self_is_AnyObject_log: String { "where Self: AnyObject" }
    }
    
    extension Programmable where Self: AnyObject & Convertible {
      var log: String { "\(where_Self_is_AnyObject_log) & Convertible" }
    }