HomeiOS Developmentios - Decode Dynamic Varieties in Swift

ios – Decode Dynamic Varieties in Swift


Here’s a answer with an added enum for the key attribute that’s used for figuring out methods to decode the object attribute

enum KeyDefinition: String, Decodable {
    case phrase, quantity
}

And the customized decoding

struct Response: Decodable {
    let knowledge: [DataObject]
}

struct DataObject: Decodable {
    let key: KeyDefinition
    let object: ObjectType

    enum CodingKeys: String, CodingKey {
        case key, object
    }

    init(from decoder: Decoder) throws {
        let container = attempt decoder.container(keyedBy: CodingKeys.self)
        key = attempt container.decode(KeyDefinition.self, forKey: .key)
        change key {
        case .quantity:
            let quantity = attempt container.decode(Int.self, forKey: .object)
            object = ObjectType.numbers(quantity)
        case .phrase:
            let string = attempt container.decode(String.self, forKey: .object)
            object = ObjectType.phrase(string)
        }
    }
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments