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?
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 })
}