【问题标题】:Is it possible to declare a protocol with an associatedtype inside a protocol?是否可以在协议中声明具有关联类型的协议?
【发布时间】:2021-11-19 05:33:22
【问题描述】:

我想在协议中声明一个带有关联类型的协议。

我知道将其声明为类而不是协议可以解决问题。

但我想在协议中使用它。

有没有办法使用泛型或类型别名之类的东西在协议中使用具有关联类型的协议?

protocol A {
    associatedtype T
}

protocol B {
    var a: A { get } // error. protocol 'A' can only be used as a generic constraint because it has Self or associated type requirements
                     // But I want set a.T = Int
}

【问题讨论】:

  • B 中的A 也可以是关联类型,您可以扩展B 其中A 将是另一个协议

标签: swift


【解决方案1】:

如果您真的想将A.T 设置为Int,您可以在B 内的关联类型where 子句中指定:

protocol A {
    associatedtype T
}

protocol B {
    associatedtype U: A where U.T == Int 
    var a: U { get }
}

或者,您不想将B 锁定到一个特定的A.T 类型,您可以引入另一个associatedtype,它链接回A

protocol A {
    associatedtype T
}

protocol B {
    associatedtype T
    associatedtype U: A where U.T == T 
    var a: U { get }
}

参见Swift 编程语言中的Associated Types with a Generic Where Clause

【讨论】:

    【解决方案2】:
    protocol A {
        associatedtype T
        var a: T { get }
    }
    
    protocol B {
        associatedtype U where U: A
        var b: U { get }
    }
    

    请记住,由于这两种关联类型,您将不得不对此进行大量推理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-13
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多