可编码结构包含协议属性 [英] A codable structure contains a protocol property

查看:32
本文介绍了可编码结构包含协议属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从 codable 继承的协议

I have a protocol which is inherited from codable

protocol OrderItem:Codable {
    var amount:Int{get set}
    var isPaid:Bool{get set}
} 

一个结构体符合这个协议

And a struct conform this protocol

struct ProductItem:OrderItem {
    var amount = 0
    var isPaid = false
    var price = 0.0
}

但是,当我将此结构放入可编码结构时,出现错误

However when I put this structure into a codable structure, I got errors

struct Order:Codable {
    var id:String
    var sn:String = ""
    var items:[OrderItem] = []
    var createdAt:Int64 = 0
    var updatedAt:Int64 = 0
}

错误是

Type 'Order' does not conform to protocol 'Encodable'
Type 'Order' does not conform to protocol 'Decodable'

但是如果我将 items:[OrderItem] 更改为 items:[ProductItem] ,一切正常!

But if I change items:[OrderItem] to items:[ProductItem] , everything works!

我该如何解决这个问题?

How can I fix this problem?

推荐答案

你不能那样做,因为协议只说明你必须做什么.所以当你让你的协议 X 符合 Codable 时,只意味着任何符合 X 的类型也必须符合 Codable 但它不会提供所需的实现.您可能会感到困惑,因为 Codable 不需要您在所有类型都已经是 Codable 的情况下实现任何内容.如果 Codable 要求您实现一个名为 myFunction 的函数,那么您的 OrderItem 将缺少该函数的实现,并且编译器将使你添加它.

You cannot do that because a protocol only states what you must do. So when you conform your protocol X to Codable, it only means that any type that conforms to X must also conform to Codable but it won't provide the required implementation. You probably got confused because Codable does not require you to implement anything when all your types already are Codable. If Codable asked you to, say, implement a function called myFunction, your OrderItem would then lack the implementation of that function and the compiler would make you add it.

您可以这样做:

struct Order<T: OrderItem>: Codable {
   var id:String
   var sn:String = ""
   var items: [T] = []
   var createdAt:Int64 = 0
   var updatedAt:Int64 = 0
}

您现在说 items 是符合 OrderItem 的通用类型.

You now say that items is a generic type that conforms to OrderItem.

这篇关于可编码结构包含协议属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆