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

Protocol restriction on another protocol associated type

我有一个协议 MyProtocol,它有一个 associatedtype,由 myFunction

的 return 类型推断
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.
    }
}

从那里一切正常。不,我想构建另一个只能应用于 MyProtocol if associatedtype is Codable :

的协议
protocol MyProtocolCodable where Self: MyProtocol, MyType == Codable? {}

代码在此之前运行良好,但是当我尝试将它应用到我的 class 时,出现错误:

extension MyClass1: MyProtocolCodable{} 

'MyProtocolCodable' requires the types 'MyStruct?' and 'Codable?' (aka 'Optional<Decodable & Encodable>') be equivalent

然而,据我所知,MyStruct?(又名可选)和 Codable?(又名可选)是等价的吗?

我怎样才能摆脱这个错误信息?我是不是在做一些不应该做的事情?

As far as I can see MyStruct? (aka Optional) and Codable? (aka Optional<Decodable & Encodable>) are equivalent?

不,他们不是。 MyStruct 符合 Codable 但不等价

如:每个 MyStruct 都是 Codable 但不是每个 Codable 都是 MyStruct


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

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

因为 MyStruct 不等于 Codable?.