如何使用Swift中具有类型的协议的约束引用泛型类?

时间:2021-10-02 14:28:56

I'm try to define a protocol P2 so that it returns a generic class with a constraint on another protocol P1, e.g:

我试着定义一个协议P2,以便它返回一个对另一个协议P1有约束的泛型类,例如:

protocol P1 {}

class C<T : P1> {}

public protocol P2 {
    typealias T
    class func c() -> C<T>
}

But this results in the following compiler error:

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

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

There doesn't seem to be any combination that allows this, e.g. the next obvious syntax:

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

protocol P1 {}

class C<T : P1> {}

public protocol P2 {
    typealias T
    class func c() -> C<T : P1>
}

Errors with:

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

Is this possible to do in Swift?

这可以在Swift中做到吗?

1 个解决方案

#1


6  

I have never used constraints like that, but I think you can just define it in the typealias - I've tried it in a playground and compilation succeeds:

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

typealias T: P1

#1


6  

I have never used constraints like that, but I think you can just define it in the typealias - I've tried it in a playground and compilation succeeds:

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

typealias T: P1