简体   繁体   English

对另一个协议关联类型的协议限制

[英]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.
    }
}
  • In MyClass1 , associatedtype is infered as MyStruct?MyClass1中, associatedtype类型被推断为MyStruct?
  • In 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.

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