1

I regularly update some values in my app via a configuration JSON that I host on my server.

I have a singleton struct with default values, fetch the json and update the values in the singleton's struct. So far so good.

Now I'd prefer to not have all possible keys online if they are unused; I'd rather only have e.g. 2 or 3 keys in my JSON that need updating and the rest of the keys can remain the same as they are in the app binary.

The answers in With JSONDecoder in Swift 4, can missing keys use a default value instead of having to be optional properties? tackle this at wide variety however every single one of these solutions comes with a lot of code duplication (or at least having to mention each variable 2 to 4 times for the default values to apply in case of missing JSON keys).

Maybe there is a better solution for this, either via JSON, or via anything else. I'd prefer not to use services like Firebase Remote Config for things I can probably write by myself much more lighter too.

Somewhat of a solution to the "skip missing keys" problem is to simply use optionals however then I have the burden of guarding against nil everywhere in my code. I could probably also simply force-unwrap these everywhere since I know they exist in any case but this is quite dangerous for example in the case of me introducing a new key and forgetting to also provide a default value.

I've also thought about using protobuf for this since the pure data is way less "readable" in regards to exposing all possible keys however that seems too much of a hassle to use.

Is there any other approach I could take to tackle this? My current code is the same setup as the asker in With JSONDecoder in Swift 4, can missing keys use a default value instead of having to be optional properties? uses

user2330482
  • 1,053
  • 2
  • 11
  • 19

0 Answers0