user2330482
user2330482

Reputation: 1103

Swift: Access struct/class variables by string name

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.

Upvotes: 1

Views: 248

Answers (0)

Related Questions