其他协议关联类型的协议限制

时间:2020-07-24 09:29:45

标签: swift protocols associated-types

我有一个协议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?(又名)是等效的吗?

如何摆脱此错误消息?我在做不该做的事吗?

1 个答案:

答案 0 :(得分:1)

据我所见MyStruct? (aka可选)和Codable? (又名 可选的)是否等效?

不,不是。 MyStruct 符合Codable,但与它等效

例如:每个MyStruct都是可编码的,但并非每个可编码都是MyStruct


您可以尝试将MyType == Codable?更改为MyType: Codable

protocol MyProtocolCodable where Self: MyProtocol, MyType: Codable {}

因为MyStruct不等于Codable?