快速创建具有动态名称的变量 [英] Create a variable in swift with dynamic name

查看:43
本文介绍了快速创建具有动态名称的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In swift, in a loop managed by an index value that iterates, I want to create a variable which has the variable name that is a concatenation of "person_" and the current loop index.

所以我的循环最终创建了如下变量:

So my loop ends up creating variables like:

var person_0 = ...
var person_1 = ...
var person_2 = ...
etc...

我没有网上搜索的好运,所以在这里发布。

I had no luck searching online so am posting here.

谢谢!

推荐答案

一种解决方案是将所有变量存储在数组中。您在该数组中存储的变量的索引将与您要在变量名称中包括的索引值相对应。

One solution is to store all your variables in an array. The indexes for the variables you store in that array will correspond to the index values you're trying to include in the variable name.

在以下位置创建实例变量您的视图控制器:

Create an instance variable at the top of your view controller:

var people = [WhateverTypePersonIs]()

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

Then create a loop that will store however many people you want in that instance variable:

for var i = 0; i < someVariable; i++ {
    let person = // someValue of type WhateverTypePersonIs
    people.append(person)
}

例如,如果您需要以尝试解决问题的方式获得 person_2,则可以使用 people []来访问该人。 2]

If you ever need to get what would have been "person_2" with the way you were trying to solve your problem, for example, you could access that person using people[2].

这篇关于快速创建具有动态名称的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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