Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Decodable with extra property

I have a Decodable to which I want to add one extra property, not present in the plist.

The code below seems to work. I’m not sure why, since it no longer conforms to the plist. Can anyone explain?

Is there any better of doing it without having to write a custom init and CodingKeys?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct Phrases: Decodable {
  let animal: Dictionary<String, String>
  let food: Dictionary<String, String>
  let color: Dictionary<String, String>
}

extension Phrases {
  var nouns: Dictionary<String, String> {
    var nouns = [String: String]()
    nouns += self.animal
    nouns += self.food
    return nouns
  }
}

(The += is a custom operator for the Dictionary merge function.)

>Solution :

This new property that you have added is a computed property, not a stored property like animal, food and color.

The synthesised Decodable implementation is only derived from the stored properties of the struct, so adding a computed property does not change the synthesised Decodable implementation at all.

The semantics of computed property is that its value is computed every time you access it (call its getter). Every time you say nouns, the code in the body runs, creating a new dictionary by computing the merge of the two dictionaries.

If that is the semantics you want, then doing this is not problematic at all. Do note that the getter can be simplified with merging:

 var nouns: [String: String] {
    // replace with whatever merging function you have used
    animal.merging(food, uniquingKeysWith: { key1, key2 in key2 })
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading