我有一个协议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
被推断为MyStruct?
MyClass2
中,associatedtype
被推断为Int?
从那里一切正常。不,我想构建另一个协议,如果associatedtype是可编码的,则只能应用于 MyProtocol :
protocol MyProtocolCodable where Self: MyProtocol, MyType == Codable? {}
代码运行正常,直到此处,但是当我尝试将其应用于我的班级时,出现错误:
extension MyClass1: MyProtocolCodable{} ?
“ MyProtocolCodable”需要类型“ MyStruct?”。和“可编码?” (aka'Optional
')等同
据我所知MyStruct?
(又名Optional)和Codable?
(又名
如何摆脱此错误消息?我在做不该做的事吗?
答案 0 :(得分:1)
据我所见MyStruct? (aka可选)和Codable? (又名 可选的
)是否等效?
不,不是。 MyStruct
符合至Codable
,但与它等效。
例如:每个MyStruct都是可编码的,但并非每个可编码都是MyStruct 。
您可以尝试将MyType == Codable?
更改为MyType: Codable
:
protocol MyProtocolCodable where Self: MyProtocol, MyType: Codable {}
因为MyStruct
不等于Codable?
。