如何在模型中使用 swift 协议

How to work with swift protocols in models

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' can only be used as a generic constraint because it has Self or associated type requirements

我们怎样才能最好地反序列化这样的 JSON?

最好像这样设置结构,而不是两个单独的对象。

那么您也许可以在 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
    }