具有关联类型的Swift协议 - 类型可能不会将自身引用为要求

Ada*_*ter 5 protocols swift protocol-op

我有以下协议及其扩展

public protocol RESEndpointReachable: CustomDebugStringConvertible
{
    associatedtype EndpointType: RESEndpointReachable


    //  MARK: - Properties

    /// The name of the endpoint as defined in the REST URI.
    var name: String { get }

    /// An array of possible next endpoints that this endpoint can reach. E.g account's next endpoints would be authenticate and unauthenticate.
    var nextPossibleEndpoints: [EndpointType] { get }


    //  MARK: - Ability

    /// Used to process the endpoint.
    func processRequest(request: RERequest)

    /// Processes the next endpoint that matches the name `name`. Expects an endpoint with the name `name` to exist in `nextPossibleEndpoints`.
    func processNextEndpointWithName(name: String, request: RERequest)
}

public extension RESEndpointReachable
{
    //  MARK: - CustomDebugStringConvertible

    public var debugDescription: String {
        return name
    }


    //  MARK: - RESEndpointReachable

    var nextPossibleEndpoints: [EndpointType] {
        return []
    }

    public func processRequest(request: RERequest)
    {
        //  Check all possible endpoints are being processed
        if let nextEndpoint = nextPossibleEndpoints.first
        {
            fatalError("Unhandled endpoint \(nextEndpoint).")
        }
    }

    public func processNextEndpointWithName(name: String, request: RERequest)
    {
        //  Get the next endpoint that matches the specified name
        let nextEndpoints = nextPossibleEndpoints.filter { $0.name == name }

        if nextEndpoints.count > 1
        {
            fatalError("Multiple next endpoints found with the name '\(name)'.")
        }

        guard let nextEndpoint = nextEndpoints.first else
        {
            fatalError("No next endpoint with the name '\(name)'.")
        }


        //  Process the next endpoint
        nextEndpoint.processRequest(request)
    }
}
Run Code Online (Sandbox Code Playgroud)

在构建时,该行associatedtype EndpointType: RESEndpointReachable有以下错误:Type may not reference itself as a requirement.但据我所知,这就是你在Swift中使用相关类型的方法.

正如您可能已经猜到的那样,我总是希望EndpointType最终被设置为继承的类型RESEndpointReachable.

Aus*_*inZ 4

该功能被 Swift 团队称为“递归协议约束”,并且已列入 Swift 未来版本中添加的路线图。有关此功能和其他计划功能的更多信息,请查看 Swift 团队的“完成泛型”宣言