代码之家  ›  专栏  ›  技术社区  ›  J. Doe

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

  •  1
  • J. Doe  · 技术社区  · 6 年前

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

    正如您在代码中的注释中所看到的,我想知道是否可以约束associatedtypes,使其与其他协议中的其他associatedtypes相同。目标是省略演员阵容。现在,实现类可以为其选择不同的类型 requestType

    1 回复  |  直到 6 年前
        1
  •  2
  •   ryanecrist    6 年前

    这个 requestType 中不需要关联的类型 RequestProcessor 协议,因为它是基于 requester 关联类型。

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

    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