Nash Porter Nash Porter - 2 months ago 9
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",
"DJ",
"SJ",
"XJ",
"Comanche",
"YJ",
"TJ",
"JK"
//"Grand Cherokee",
//"Renegade",
//"Compass",
//"Commander",
//"Liberty",
//"Patriot",
//"Wagoneer"
]

var CJ: [String] = ["CJ-1",
"CJ-2",
"CJ-2A",
"CJ-V35",
"CJ-4",
"CJ-4M",
"CJ-4MA",
"CJ-3B",
"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-6",
"CJ-3B Long",
"CJ-5A",
"CJ-6A",
"CJ-7",
"CJ-5",
"CJ-8: Scrambler",
"CJ-10"
]


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...

Answer

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"