HomeiOS Developmentdecodable - What's flawed with my enum decoding in Swift?

decodable – What’s flawed with my enum decoding in Swift?


If you use a non-String non-Int sort because the dictionary key, Dictionary‘s Decodable implementation expects an array of key worth pairs, i.e.:

["de", "foo", "en", "bar"]

This decodes to [.deutsch: "foo", .english: "bar"].

JSON keys can solely be strings in any case, and the Decodable implementation does not know how you can convert a random Decodable worth right into a string. It may have been made to test for RawRepresentable with RawValue == String, nevertheless it wasn’t.

One factor that it does test for although, is CodingKeyRepresentable, should you simply conform Lg to that, then you’ll be able to decode a JSON dictionary accurately.

Conforming a kind to CodingKeyRepresentable permits you to decide in to encoding and decoding Dictionary values keyed by the conforming sort to and from a keyed container, somewhat than encoding and decoding the dictionary as an unkeyed container of alternating key-value pairs.

extension Lg: CodingKeyRepresentable, CodingKey {
    init?(codingKey: T) the place T : CodingKey {
        self.init(rawValue: codingKey.stringValue)
    }
    
    var codingKey: CodingKey {
        self
    }
}

Observe that I additionally conformed it to CodingKey to make it simpler to put in writing the codingKey property required by CodingKeyRepresentable.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments