Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
rinold opened this issue Jan 27, 2018 · 2 comments
Closed

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

rinold opened this issue Jan 27, 2018 · 2 comments

Comments

@rinold
Copy link

rinold commented Jan 27, 2018

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 :[

@norio-nomura
Copy link
Collaborator

Thank you for reporting!
This is a bug of Yams. #100
I'll open a PR for fixing that.

norio-nomura added a commit that referenced this issue Jan 28, 2018
@rinold
Copy link
Author

rinold commented Jan 28, 2018

Hi @norio-nomura,

Thank you for so fast reply and fix, this is really awesome :)

P.S. I've tried the branch with fix and it worked like a charm on my test openAPI(swagger) files!
Looking forward for next Yams release, thanks!)

@jpsim jpsim closed this as completed Apr 29, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants