在另一个协议中重用协议中的关联类型

Reuse associated type from protocol in another protocol

这是我的代码:

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
        }
    }
}

正如您在代码中的注释中看到的那样,我想知道我是否可以约束关联类型,使其与另一个协议中的其他关联类型相等。目标是省略演员表。现在,实现 class 可以为 requestType 选择不同的类型,这将导致崩溃。

requestType 关联类型在 RequestProcessor 协议中不是必需的,因为它基于 requester 关联类型是隐式的。

您应该能够像这样定义 RequestProcessor 协议:

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

并像这样使用它:

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

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

现在,process() 方法中的 response 闭包参数将采用 MyRequester 协议的关联类型(在本例中为 Int),所以没有铸造是必要的。