加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:41:30 所属栏目:百科 来源:网络整理
导读:我有以下协议及其扩展 public protocol RESEndpointReachable: CustomDebugStringConvertible{ associatedtype EndpointType: RESEndpointReachable // MARK: - Properties /// The name of the endpoint as defined in the REST URI. var name: String { ge
我有以下协议及其扩展

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

在构建时,相关联的行类型EndpointType:RESEndpointReachable具有以下错误:类型可能不会将自身引用为要求.但据我所知,这就是你在Swift中使用相关类型的方法.

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

解决方法

Swift团队将此功能称为“递归协议约束”,并在未来版本的Swift中添加路线图.有关此计划功能和其他计划功能的更多信息,请查看Swift团队的 ‘Completing Generics’ manifesto.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读