2

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.

jscs
  • 63,694
  • 13
  • 151
  • 195

2 Answers2

1

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.

  • Yes. this seems more like the solution. I will understand it more and implement in on my problem. Thanks again. – Tapas Kumar Pradhan Aug 28 '17 at 22:14
  • 1
    I'd like to add that it's better to use dictionary, map, hashtable, etc than trying to dynamically access variables by string name in pretty much all cases but not just in swift, also in php and others. Why? Security and structure. – HumbleWebDev Aug 29 '17 at 00:55
  • I never thought about that. I come from a, um, Assembler/COBOL start in the early 1980s and *forget* that side of things. Great addition! –  Aug 29 '17 at 01:01
0

Use an array

let myArray = ["one", "two", "three"];
var counter = 1;
print(myArray[counter]);
HumbleWebDev
  • 555
  • 4
  • 20