Swift: Converting a string into a variable name

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.

Leave a Comment