vendredi 27 décembre 2019

Swift Protocol referencing itself and associated type

I have a classic implementation of Chain of Responsibility pattern with the following code:

protocol Request {

    var firstName: String? { get }
    var lastName: String? { get }

    var email: String? { get }
    var password: String? { get }
    var repeatedPassword: String? { get }
} 

protocol Handler {

    var next: Handler? { get }

    func handle(_ request: Request) -> LocalizedError?
}

class BaseHandler: Handler {

    var next: Handler?

    init(with handler: Handler? = nil) {
        self.next = handler
    }

    func handle(_ request: Request) -> LocalizedError? {
        return next?.handle(request)
    }
}

So I can create a PermissionHandler, LocationHandler, LoginHandler, a SignupHandler and combine them in chain. So far so good.

Now I want to create a Chain of Responsibility for other purposes, let's say a MediaContentPlayer CoR with different types of MediaContentHandlers and I thought to refactor and reuse the base code using generics.

So I started from the Handler protocol:

protocol Handler {

    associatedtype HandlerRequest
    var next: Handler? { get }

    func handle(_ request: HandlerRequest) -> LocalizedError?
}

but I get error "Protocol 'Handler' can only be used as a generic constraint because it has Self or associated type requirements".

Is there a way to reference the protocol inside the protocol itself when using associatedtype? Or another way to make the above code not dependent on a specific type?

Aucun commentaire:

Enregistrer un commentaire