Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Converting a string into a variable name

Tags:

swift

I have variables with incremented numbers within, such as row0text, row1text, row2text, etc.

I've figured out how to dynamically create string versions of those variable names, but once I have those strings, how can I use them as actual variable names rather than strings in my code?

Example:

var row3text = "This is the value I need!"

var firstPart = "row"
var rowNumber = 3
var secondPart = "text"

var together = (firstPart+String(rowNumber)+secondPart)

// the below gives me the concatenated string of the three variables, but I'm looking for a way to have it return the value set at the top.
println (together)

Once I know how to do this, I'll be able to iterate through those variables using a for loop; it's just that at the moment I'm unsure of how to use that string as a variable name in my code.

Thanks!

like image 684
hudsonian Avatar asked Dec 05 '14 17:12

hudsonian


1 Answers

Short Answer: There is no way to do this for good reason. Use arrays instead.

Long Answer: Essentially you are looking for a way to define an unknown number of variables that are all linked together by their common format. You are looking to define an ordered set of elements of variable length. Why not just use an array?

Arrays are containers that allow you to store an ordered set or list of elements and access them by their ordered location, which is exactly what you're trying to do. See Apple's Swift Array Tutorial for further reading.

The advantage of arrays is that they are faster, far more convenient for larger sets of elements (and probably the same for smaller sets as well), and they come packaged with a ton of useful functionality. If you haven't worked with arrays before it is a bit of a learning curve but absolutely worth it.

like image 63
CorbinMc Avatar answered Sep 23 '22 12:09

CorbinMc