将结构放入数组

时间:2018-09-20 22:58:12

标签: swift

我想将结构放入数组中。我只是不能,我无法想象这是不可能的。

到目前为止,我的代码是:

struct PersonA {
     var name: String
     var surname: String
     var phone: Int }

var contactsA: [PersonA] = []

var person1: PersonA = PersonA (name: "Jack", surname: "Johnson", phone: 2)
var person2: PersonA = PersonA (name: "alex", surname: "a", phone: 3)

contactsA.append (person1)
contactsA.append (person2)

for contact in contactsA {
     print ("\ (contact.name) \ (contact.surge)")
}

在此代码中,我使用vars person1和person2。我必须进行大量的联系,因此我希望不必为每个联系人创建单独的变量。

2 个答案:

答案 0 :(得分:4)

如果要添加联系人而不将其绑定到变量,请执行以下操作:

struct PersonA {
    var name: String
    var surname: String
    var phone: Int
}

var contactsA: [PersonA] = []

contactsA.append(PersonA(name: "Jack", surname: "Johnson", phone: 2))
contactsA.append(PersonA(name: "alex", surname: "a", phone: 2))

for contact in contactsA {
    print("\(contact.name) \(contact.surname)")
}

答案 1 :(得分:2)

您不需要单独的变量。您有几种选择:

选项1:

var contactsA = [PersonA]()

contactsA.append(PersonA(name: "Jack", surname: "Johnson", phone: 2))
contactsA.append(PersonA(name: "alex", surname: "a", phone: 3))

选项2:

var contactsA = [
    PersonA(name: "Jack", surname: "Johnson", phone: 2)),
    PersonA(name: "alex", surname: "a", phone: 3))
]