Skip to content

Is it possible to use Dictionary as decoding type? #99

@rinold

Description

@rinold

Hi, sorry for any inconveniences beforehand, and many thanks for Yams 👍

I'm trying to decode the dictionary like so:

import Yams
let yaml = "'200': ok"
let decodedYaml = try YAMLDecoder().decode([String: String].self, from: yaml)

And getting crash:

Fatal error: Error raised at top level: Swift.DecodingError.keyNotFound(Swift._DictionaryCodingKey(stringValue: "200", intValue: Optional(200)), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key _DictionaryCodingKey(stringValue: "200", intValue: Optional(200)) ("200").", underlyingError: nil)): file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.74.1/src/swift/stdlib/public/core/ErrorType.swift, line 187

Am I doing it wrong, and how it should be then? Are there any chances this would be supported by Yams in future?

While if using JSONDecoder, this works fine and dictionary is decoded without issues:

let json = "{\"200\": \"OK\"}"
let decodedJson = try JSONDecoder().decode([String: String].self, from: json)

E.g. I have custom protocol that both JSONDecoder and YAMLDecoder are conforming but there is no magic, e.g. for json one:

extension JSONDecoder: StringDecoder {
    public func decode<T>(_ type: T.Type, from string: String) throws -> T where T : Decodable {
        guard let data = string.data(using: .utf8) else {
            throw DecodingError("Unable to extract data from string in utf8 encoding")
        }
        return try self.decode(T.self, from: data)
    }
}

P.S. Actually I just simplified it for example and I had to decode many [String: SomeGeneric<CustomType>] entries :[

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions