如何从 Swift 中带有类型别名的协议中引用带有约束的通用 class?
How to reference a generic class with a constraint from a Protocol with a typealias in Swift?
我正在尝试定义一个协议 P2
以便它 returns 是一个通用 class 并且对另一个协议 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
我正在尝试定义一个协议 P2
以便它 returns 是一个通用 class 并且对另一个协议 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