[英]Protocol restriction on another protocol associated type
我有一個協議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 是 Codable 則只能應用於 MyProtocol :
protocol MyProtocolCodable where Self: MyProtocol, MyType == Codable? {}
代碼在這里運行良好,但是當我嘗試將它應用到我的 class 時,我收到一個錯誤:
extension MyClass1: MyProtocolCodable{} 🛑
“MyProtocolCodable”需要類型“MyStruct?” 和“可編碼?” (aka 'Optional<Decodable & Encodable>') 是等價的
然而,據我所知, MyStruct?
(又名可選)和Codable?
(aka Optional<Decodable & Encodable>) 是等價的嗎?
我怎樣才能擺脫這個錯誤信息? 我在做一些不該做的事嗎?
據我所知,MyStruct? (又名可選)和可編碼? (aka Optional<Decodable & Encodable>) 是等價的嗎?
不,他們不是。 MyStruct
符合Codable
但不等同於它。
如:每個 MyStruct 都是 Codable 但不是每個 Codable 都是 MyStruct 。
您可以嘗試更改MyType == Codable?
到MyType: Codable
:
protocol MyProtocolCodable where Self: MyProtocol, MyType: Codable {}
因為MyStruct
不等於Codable?
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.