Get the value of a Swift variable from a constructed name

316 views Asked by At

I am stuck at a problem which i am trying to figure out in Swift 4.

Let say, i have the below variables

let var1 = "One"
let var2 = "Two"
let var3 = "Three"

var counter = 1

// Loop Start

let currentVariable = "var" + "\(counter)"

//Fetch the value of variable stored under currentVariable

counter += 1

//Loop end

I am trying to get the value based on variable name stored under currentVariable.

2

There are 2 answers

3
AudioBubble On BEST ANSWER

You can set up dictionary, replacing your variable names with keys.

let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var myDictionary:[String:String] = ["var1":"One", "var2":"Two", "varA":"A", "varB":"B"]  // note, both sides can be different types than String

for x in 0...9 {
    let myKey = "var" + String(x)
    printValue(myKey)
}
for x in letters.characters {
    let myKey = "var" + String(x)
    printValue(myKey)
}

The simple function:

func printValue(_ key:String) {
    let myValue = myDictionary[key]
    if myValue != nil {
        print(myValue)
    }
}

I'm pretty sure you can make things a bit more elegant, but you get the idea. Also, keep in mind that a Dictionary is "unordered", as opposed to an array.

6
HumbleWebDev On

Use an array

let myArray = ["one", "two", "three"];
var counter = 1;
print(myArray[counter]);