如何使用Swift中带有typealias的Protocol中的约束引用泛型类?

前端之家收集整理的这篇文章主要介绍了如何使用Swift中带有typealias的Protocol中的约束引用泛型类?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试着定义一个协议P2,以便它返回一个对另一个协议P1有约束的泛型类,例如:
  1. protocol P1 {}
  2.  
  3. class C<T : P1> {}
  4.  
  5. public protocol P2 {
  6. typealias T
  7. class func c() -> C<T>
  8. }

但是这会导致以下编译器错误

  1. error: type 'T' does not conform to protocol 'P1'
  2. class func c() -> C<T>

似乎没有任何组合可以允许这种情况,例如:下一个明显的语法:

  1. protocol P1 {}
  2.  
  3. class C<T : P1> {}
  4.  
  5. public protocol P2 {
  6. typealias T
  7. class func c() -> C<T : P1>
  8. }

错误

  1. error: expected '>' to complete generic argument list
  2. class func c() -> C<T : P1>
  3. ^
  4. note: to match this opening '<'
  5. class func c() -> C<T : P1>

这可以在Swift中做到吗?

我从来没有使用过这样的约束,但我认为你可以在类型中定义它 – 我在游乐场尝试过它并且编译成功:
  1. typealias T: P1

猜你在找的Swift相关文章