我试着定义一个协议P2,以便它返回一个对另一个协议P1有约束的泛型类,例如:
- protocol P1 {}
- class C<T : P1> {}
- public protocol P2 {
- typealias T
- class func c() -> C<T>
- }
但是这会导致以下编译器错误:
- error: type 'T' does not conform to protocol 'P1'
- class func c() -> C<T>
似乎没有任何组合可以允许这种情况,例如:下一个明显的语法:
- protocol P1 {}
- class C<T : P1> {}
- public protocol P2 {
- typealias T
- class func c() -> C<T : P1>
- }
错误:
- error: expected '>' to complete generic argument list
- class func c() -> C<T : P1>
- ^
- note: to match this opening '<'
- class func c() -> C<T : P1>
这可以在Swift中做到吗?
我从来没有使用过这样的约束,但我认为你可以在类型中定义它 – 我在游乐场尝试过它并且编译成功:
- typealias T: P1