简体   繁体   中英

Reuse associated type from protocol in another protocol

This is my code:

protocol Requester {
    associatedtype requestType

    var response: ((requestType) -> ())? { get set }
}

protocol RequestProcesser: AnyObject {
    // Is it possible to define a associated type that is equal to the associated type of Requester?
    associatedtype requester: Requester

    // This associatedtype should always be equal to Requester.requestType
    associatedtype requestType

    var request: requester { get set }
}

extension RequestProcesser {
    func process() {
        request.response = { response in

            // Now I need to cast...
            // Is there any way around this?
            // the type of the response should be equal to requestType so the cast can be omitted right?
            let x = response as! requestType
        }
    }
}

As you can read in the comments in the code, I am wondering if I can constraint associatedtypes in a way they are equal to other associatedtypes in another protocol. The goal is to omit the cast. Now an implementing class can choose a different type for requestType , which will result in a crash.

The requestType associated type isn't necessary in the RequestProcessor protocol, as it is implicit based on the requester associated type.

You should just be able to define the RequestProcessor protocol like this:

protocol RequestProcesser: AnyObject {
    associatedtype requester: Requester
    var request: requester { get set }
}

And use it like this:

class MyRequester: Requester {
    typealias requestType = Int
    var response: ((Int) -> ())?
}

class MyRequestProcessor: RequestProcesser {
    typealias requester = MyRequester
    var request = MyRequester()
} 

Now, the response closure parameter inside the process() method will take on the associated type of the MyRequester protocol (in this case Int ), so no casting is necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM