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

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


Once you use a non-String non-Int kind 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 spite of everything, and the Decodable implementation would not know easy methods to convert a random Decodable worth right into a string. It might have been made to verify for RawRepresentable with RawValue == String, however it wasn’t.

One factor that it does verify for although, is CodingKeyRepresentable, if you happen to simply conform Lg to that, then you possibly can 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 kind to and from a keyed container, reasonably 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
    }
}

Be aware that I additionally conformed it to CodingKey to make it simpler to write down 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