Swift protocol oriented programming one protocol inherit others and one of them implement method

59 views Asked by At

I have such protocols

public protocol IRouter: Requestable, MultipartUploading, Encoder {

}

where IRouter should be inheriting or conformming to both Requestable and Encoder protocol

public protocol Requestable {
    
    func asURLRequest() throws -> URLRequest
}

And MultipartUploading is another protocol with default implementation

public protocol MultipartUploading {
        
        func multipartFormData() throws -> Data?
    }
    
    public extension MultipartUploading {
        func multipartFormData() throws -> Data? { return nil }
    }

Then I add default implementation to Requestable if it is also IRouter

public extension Requestable where Self: IRouter {
    
    func asURLRequest() throws -> URLRequest {
      // make url request
    }

}

and also another implementation to MultipartUploading protocol

public extension MultipartUploading where Self: IRouter {
    
    func multipartFormData() -> Data? {
      // make data to upload
    }
}

But then If I import module to Application target and do

enum Router: IRouter {  }

It does not contain this multipartFormData and asUrlRequest implementation and fore me to implement them again? how to avoid this and have this default implementations. It seems if I do this in the same module (target) then Router: IRouter does not complain, but maybe it is just Xcode not detecting bug

1

There are 1 answers

2
Alexander Gaidukov On

This extensions look redundant.

public extension Requestable where Self: IRouter
public extension MultipartUploading where Self: IRouter

The thing is IRouter is a protocol, that inherits Both Requestable and MultipartUploading. So, you can replace both extensions with a single one.

public extension IRouter {
    func asURLRequest() throws -> URLRequest {
      // make url request
    }
    func multipartFormData() -> Data? {
      // make data to upload
    }
}

It should also fix your issue.