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

时间:2018-11-17 11:48:39

标签: swift protocols associated-types

这是我的代码:

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

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

1 个答案:

答案 0 :(得分:2)

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

现在,response方法内的process()闭包参数将采用MyRequester协议的关联类型(在本例中为Int),因此无需强制转换