简体   繁体   English

如何在Swift中创建具有多个变量的数组

[英]How Do I Create An Array With Multiple Variables In Swift

I am new to iOS development, and for some reason I can't figure out how to do this even though I realize it has to be simple. 我是iOS开发的新手,由于某种原因,即使我意识到它必须很简单,也无法弄清楚该如何做。 I want to create a collection with 2 string values. 我想用2个字符串值创建一个集合。 For instance: 例如:

var firstName = "Bob"
var lastName = "Smith"

So the first index would contain ("Bob", "Smith") and so one for each first and last name I want to add to the collection. 因此,第一个索引将包含(“ Bob”,“ Smith”),因此我要添加到集合中的每个姓氏和名字都包含一个。 What object do I use? 我使用什么对象? I tried a dictionary but it seems you have to add your values to that up front, and I need to add my later on programmatically. 我试过字典,但看来您必须在前面添加值,而我以后需要以编程方式添加。

You could use a dictionary but I'd create a Person struct that contains a firstName and a lastName and put those into an array. 您可以使用字典,但是我将创建一个包含firstName和lastName的Person结构并将它们放入数组中。

struct Person {
    var firstName: String
    var lastName: String
}

var firstName = "Bob"
var lastName = "Smith"

var array = [Person(firstName: firstName, lastName: lastName)]

It also has the benefit of being able to access the parts using .firstName and .lastName 它还具有能够使用.firstName.lastName访问部件的好处。

array[0].firstName

As opposed to a dictionary that that requires a string 与需要字符串的字典相反

array[0]["firstName"]

To create an array with only string you use 要创建仅包含字符串的数组,请使用

var shoppingList: [String] = ["Eggs", "Milk"]

And to add to the end of the array (push) you use 并添加到数组的末尾(推),您可以使用

shoppingList.append("Bread")

首选struct方法,但是如果您想做一些与初始请求更类似的事情,则可以做一个元组数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM