Search code examples
jsonswiftmodeldeserializationjson-deserialization

How to work with swift protocols in models


JSON:

"sittingFurniture":[
{
    "sittingObjectType": "chair",
    "fabric": "textile"
},
{
    "sittingObjectType":"bed",
    "height": 70
},
...
]

Swift code:

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

How can we best deserialize such JSON?


Solution

  • It might be better to set up your structure like this, instead of two separate objects.

    Then you might be able to use JSONDecoder on FurnitureList

        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
        }