[英]Protocol restriction on another protocol associated type
I have a protocol MyProtocol
which has an associatedtype
, inferred by the return type of myFunction
我有一个协议
MyProtocol
,它有一个associatedtype
,由myFunction
的返回类型推断
struct MyStruct: Codable {
var myVar: Int
}
protocol MyProtocol {
associatedtype MyType
func myFunction()-> MyType
}
class MyClass1: MyProtocol {
func myFunction()-> MyStruct? {
return MyStruct(myVar: 1) //ex.
}
}
class MyClass2: MyProtocol {
func myFunction()-> Int? {
return 1 // ex.
}
}
MyClass1
, associatedtype
is infered as MyStruct?
MyClass1
中, associatedtype
类型被推断为MyStruct?
MyClass2
, associatedtype
is infered as Int?
MyClass2
中, associatedtype
类型被推断为Int?
from there everything works fine.从那里一切正常。 No I want to build another protocol that can only be applied to a MyProtocol if associatedtype is Codable :
不,我想构建另一个协议,如果 associatedtype 是 Codable 则只能应用于 MyProtocol :
protocol MyProtocolCodable where Self: MyProtocol, MyType == Codable? {}
the code runs fine until here but when I try to apply it to my class I get an error:代码在这里运行良好,但是当我尝试将它应用到我的 class 时,我收到一个错误:
extension MyClass1: MyProtocolCodable{} 🛑
'MyProtocolCodable' requires the types 'MyStruct?'
“MyProtocolCodable”需要类型“MyStruct?” and 'Codable?'
和“可编码?” (aka 'Optional<Decodable & Encodable>') be equivalent
(aka 'Optional<Decodable & Encodable>') 是等价的
yet, as far as I can see MyStruct?
然而,据我所知,
MyStruct?
(aka Optional) and Codable?
(又名可选)和
Codable?
(aka Optional<Decodable & Encodable>) are equivalent? (aka Optional<Decodable & Encodable>) 是等价的吗?
How can I get rid of this error message?我怎样才能摆脱这个错误信息? Am I doing something that is not meant to be done?
我在做一些不该做的事吗?
As far as I can see MyStruct?
据我所知,MyStruct? (aka Optional) and Codable?
(又名可选)和可编码? (aka Optional<Decodable & Encodable>) are equivalent?
(aka Optional<Decodable & Encodable>) 是等价的吗?
No, they are not.不,他们不是。
MyStruct
conforms to Codable
but is not equivalent of it. MyStruct
符合Codable
但不等同于它。
As in: every MyStruct is Codable but not every Codable is MyStruct .如:每个 MyStruct 都是 Codable 但不是每个 Codable 都是 MyStruct 。
You can try changing MyType == Codable?
您可以尝试更改
MyType == Codable?
to MyType: Codable
:到
MyType: Codable
:
protocol MyProtocolCodable where Self: MyProtocol, MyType: Codable {}
as MyStruct
is not equal to Codable?
因为
MyStruct
不等于Codable?
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.