I am looking for a better way to access the variables of a struct. A json query fills an array of this struct:
struct AnimalInfo: Codable {
var English: String
var French: String
var Spanish: String
}
An example:
let theDog = AnimalInfo(English: "Dog", French: "Chien", Spanish: "Perro")
The languages are in an array, the current one is always changing. I keep track with a pointer:
let languageListArray = ["English", "French", "Spanish"]
let currentLanguage = languageListArray[2]
I'd like to be able to retrieve the value from the struct with this information, something along the lines of:
let myString = theDog.currentLanguage // = "Perro"
.. but of course that is not possible. The best I've come up with so far is a switch:
switch currentLanguage {
case "English":
return theDog.English
case "French":
return theDog.French
case "Spanish":
return theDog.Spanish
}
But this is ugly, and doesn't scale well with many languages! Anyone have a better way?
CodePudding user response:
but of course that is not possible
Oh, it is possible if you use key paths
struct AnimalInfo: Codable {
let english: String
let french: String
let spanish: String
}
let theDog = AnimalInfo(english: "Dog", french: "Chien", spanish: "Perro")
let languageListArray : [KeyPath<AnimalInfo,String>] = [\.english, \.french, \.spanish]
let currentLanguage = languageListArray[2]
let myString = theDog[keyPath: currentLanguage] // = "Perro"