1

I would like to access a variables by its literal name in string form.

So far I've found two ways:

https://stackoverflow.com/a/51090177/2330482 which doesn't let me write to the variables

Doing https://stackoverflow.com/a/44461705/2330482 which crashes the app if the key is not found (I don't want to run that risk). If there is a way to check if the key exists first, that would likely resolve my problem. I could combine this with Mirror in the first linked answer to get all keys (and therefore know they exist) before accessing them via .value(forKey) but this seems a bit unsafe. Is there another way to catch the crash if there is no key, or another way for NSObject to first make sure the key doesn't exist?

The reason why I want to do this is to make a struct fallback to default values if an incomplete JSON is fed. If I'm able to safely access variables by their name I could probably solve this problem without having to write Codable implementations for each variable in the struct.

user2330482
  • 1,053
  • 2
  • 11
  • 19
  • Doesn't Codable already support default values? – Alexander Jan 19 '23 at 16:34
  • Could you explain your use case a bit more? Maybe there is a better solution. – Suboptimierer Jan 19 '23 at 16:39
  • All you need is a custom codable implementation – lorem ipsum Jan 19 '23 at 16:41
  • Basically I want to do this: https://stackoverflow.com/questions/44575293/with-jsondecoder-in-swift-4-can-missing-keys-use-a-default-value-instead-of-hav without having to handle each variable "manually" by writing a handler for the codable extension etc. Being able to, in code, loop through every variable, replace it with the value of the new JSON or keeping the value if the key is not present in the new JSON. – user2330482 Jan 19 '23 at 16:51
  • I want to avoid having to type out extra code for each variable in my struct. I want to "mention" each variable just once when defining the struct, then be able to dynamically access these in a loop (to apply new variables to the old struct's variables as an update), without adding huge blocks of code for each variable like most of the answers propose. – user2330482 Jan 19 '23 at 16:53
  • Are you talking about class or struct types? – Joakim Danielson Jan 20 '23 at 07:11
  • I'd be fine with both, whatever works – user2330482 Jan 20 '23 at 09:11

0 Answers0