加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:39:36 所属栏目:百科 来源:网络整理
导读:我试着定义一个协议P2,以便它返回一个对另一个协议P1有约束的泛型类,例如: protocol P1 {}class CT : P1 {}public protocol P2 { typealias T class func c() - CT} 但是这会导致以下编译器错误: error: type 'T' does not conform to protocol 'P1' class
我试着定义一个协议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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读