如何在模型中使用 swift 协议 [关闭]
Posted
技术标签:
【中文标题】如何在模型中使用 swift 协议 [关闭]【英文标题】:How to work with swift protocols in models [closed] 【发布时间】:2022-01-09 04:12:44 【问题描述】:JSON:
"sittingFurniture":[
"sittingObjectType": "chair",
"fabric": "textile"
,
"sittingObjectType":"bed",
"height": 70
,
...
]
Swift 代码:
protocol SittingObject
var type: SittingObjectType
public enum SittingObjectType: Codable, Equatable
case chair
case sofa
case bed
struct FancyChair: SittingObject, Codable, Equatable
let fabric: String
let type: SittingObjectType = .chair
struct FancyBed: SittingObject, Codable, Equatable
let height: Int
let type: SittingObjectType = .bed
struct FurnitureList: Codable, Equatable
let sittingFurniture: [SittingObject] //ERROR
Protocol 'SittingObject' 只能用作通用约束,因为它具有 Self 或关联的类型要求
我们怎样才能最好地反序列化这样的 JSON?
【问题讨论】:
标题中有一个问题,文本中有另一个问题和一条错误消息。不容易理解你在问什么。 【参考方案1】:最好像这样设置你的结构,而不是两个单独的对象。
那么你也许可以在FurnitureList
上使用JSONDecoder
struct FancyFurnitureObject: SittingObject, Codable, Equatable
let fabric: String?
let height: Int?
let type: SittingObjectType
public enum SittingObjectType: Codable, Equatable
case chair
case sofa
case bed
struct FurnitureList: Codable, Equatable
let sittingFurniture: [FancyFurnitureObject] //ERROR
【讨论】:
以上是关于如何在模型中使用 swift 协议 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
如何从模型数据 Swift 创建 JSON 字符串? [关闭]