Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Variables 使用动态名称在swift中创建变量_Variables_Swift_Concatenation - Fatal编程技术网

Variables 使用动态名称在swift中创建变量

Variables 使用动态名称在swift中创建变量,variables,swift,concatenation,Variables,Swift,Concatenation,在swift中,在一个由迭代的索引值管理的循环中,我想创建一个变量,该变量的变量名是“person_”和当前循环索引的串联 因此,我的循环最终会创建如下变量: var person_0 = ... var person_1 = ... var person_2 = ... etc... 我没有运气在网上搜索,所以我在这里发布 谢谢 让name=“person\(index)” 然后将名称添加到循环之前声明的可变数组中 诸如此类的事情?在swift中,您试图做的事情是不可能的。变量名仅适用于人类

在swift中,在一个由迭代的索引值管理的循环中,我想创建一个变量,该变量的变量名是“person_”和当前循环索引的串联

因此,我的循环最终会创建如下变量:

var person_0 = ...
var person_1 = ...
var person_2 = ...
etc...
我没有运气在网上搜索,所以我在这里发布

谢谢

让name=“person\(index)”

然后将名称添加到循环之前声明的可变数组中


诸如此类的事情?

在swift中,您试图做的事情是不可能的。变量名仅适用于人类(特别是在编译语言中),这意味着它们在编译阶段被剥离


但是,如果您真的想这样做,代码生成工具是一个不错的选择。找到一个合适的代码生成工具,在构建阶段运行它。

一个解决方案是将所有变量存储在一个数组中。存储在该数组中的变量的索引将与试图包含在变量名中的索引值相对应

在视图控制器的顶部创建一个实例变量:

var people=[WhateverTypePersonIs]()

然后创建一个循环,该循环将在该实例变量中存储所需人数:

for var i = 0; i < someVariable; i++ {
    let person = // someValue of type WhateverTypePersonIs
    people.append(person)
}
var i=0的
;i<1个变量;i++{
让person=//WhateverTypePersonIs类型的someValue
people.append(person)
}

例如,如果您需要以试图解决问题的方式获取“person_2”,您可以使用Swift中的
人员[2]

访问该人员,则无法创建动态变量名。您试图实现的是
阵列的典型用例

创建一个
数组
,并用您的个人数据填充它。稍后,您可以通过其索引访问人员:

var persons: [String] = []

// fill the array
for i in 0..<10 {
    persons.append("Person \(i)")
}

// access person with index 3 (indexes start with 0 so this is the 4th person)
println(persons[3])  // prints "Person 3"
var persons:[字符串]=[]
//填充数组

对我来说,这是一个坏习惯。可能有更好的解决方案来实现您的目标。若你们提供更多的上下文,我可能会提供帮助。对于UI元素,你们不能使用数组方法