Swift:将字符串转换为变量名 [英] Swift: Converting a string into a variable name

查看:61
本文介绍了Swift:将字符串转换为变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的变量中有递增的数字,例如 row0text、row1text、row2text 等.

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?

示例:

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)

一旦我知道如何执行此操作,我将能够使用 for 循环遍历这些变量;只是目前我不确定如何在我的代码中使用该字符串作为变量名.

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.

谢谢!

推荐答案

简短回答:没有办法做到这一点有充分的理由.改用数组.

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?

数组是允许您存储有序集合或元素列表并按其有序位置访问它们的容器,这正是您想要做的.如需进一步阅读,请参阅 Apple 的 Swift 数组教程.

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.

这篇关于Swift:将字符串转换为变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆