简体   繁体   English

Swift协议与使用相同类型约束的关联类型一致

[英]Swift protocol conformance with associated type using same-type constraint

I'm trying to define a protocol B which extends protocol A (the latter containing the associated type C), while using a where clause with same-type constraint as the compiler suggests. 我正在尝试定义扩展协议A的协议B(后者包含关联的类型C),同时使用具有相同类型约束的where子句,如编译器所建议的那样。 However, when doing this the code won't compile anymore. 但是,执行此操作时,代码将不再编译。 Is this a Swift bug (Swift 4 in this case)? 这是一个Swift错误(在这种情况下是Swift 4)吗?

To be more concrete, the code below does not compile with error: 更具体地说,下面的代码不会编译错误:

type 'E' does not conform to protocol 'A' 类型'E'不符合协议'A'

class D {

}

protocol A: class {
    associatedtype C: AnyObject
}

protocol B: A where C == D {

}

class E: B {

}

Changing the definition of protocol B as specified below will compile but will show this warning instead: 更改下面指定的协议B的定义将编译,但将显示此警告:

Typealias overriding associated type 'C' from protocol 'A' is better expressed as same-type constraint on the protocol 从协议“A”覆盖关联类型“C”的类型更好地表示为协议上的相同类型约束

protocol B: A {
    typealias C = D
}

The only way to make it compile without warnings is to specify the typealias in class E and using the where clause in protocol B, but this seems to duplicate the typealias unnecessary: 使其在没有警告的情况下进行编译的唯一方法是在E类中指定typealias并在协议B中使用where子句,但这似乎复制了不必要的typealias:

protocol B: A where C == D {

}

class E: B {
    typealias C = D
}

I guess same type constraint on protocol declaration is not getting read by classes when it conforms to that protocol. 我想类协议声明的类型约束在符合该协议时不会被类读取。

To avoid reduplication of typealias, you can remove same type constraint from protocol B and use extension to give typealias on protocol B. 为了避免类型化的重复,您可以从协议B中删除相同的类型约束,并使用扩展来为协议B提供类型。

class D {

}

protocol A: class {
    associatedtype C
}

protocol B: A  {
}

extension B {
    typealias C = D
}

class E: B  {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM