Nash Porter Nash Porter - 1 month ago 5x
Swift Question

How to use a string input as an array? Swift

I'm trying to take the result of one array as a string, and use this result as the name of an already existing array.

var Jeep_Model: [String] = ["CJ",
//"Grand Cherokee",

var CJ: [String] = ["CJ-1",
"CJ-5: Tuxedo Park Mark III",
"CJ-5: Camper",
"CJ-5: 462",
"CJ-5: Renegade I",
"CJ-5: Renegade II",
"CJ-5: Super Jeep",
"CJ-5: Golden Eagle",
"CJ-5: Golden Eagle California Edition",
"CJ-5: Golden Hawk",
"CJ-5: Silver Anniversary",
"CJ-3B Long",
"CJ-8: Scrambler",

So if Jeep_Model returns CJ, then I want to be able to call CJ as an array. Does this question make sense and if so, is this even possible?

Jeep_Model returns "CJ", then I want to read the array CJ.count or CJ[2] etc etc...


Variable names are evaluated at compile time you can't treat the name as a string value at runtime.

You need a dictionary, the key is the model returned from Jeep_Model, the value is the associated array.

The objects are shortened a bit

let Jeep_Model = ["CJ", "DJ", "SJ"]

let allModels  = ["CJ" : ["CJ-1", "CJ-2", "CJ-2A"], "DJ" : ["DJ... "], "SJ" : ["SJ... "]]

Now if Jeep_Model returns CJ you get the third CJ model with

let model = allModels["CJ"]![2] // -> "CJ-2A"