如何保存struct的条目

时间:2017-10-07 19:09:02

标签: swift struct append nsuserdefaults

现在我的代码打印输入的结构,但它只能打印输入的最后一个条目。它只能存储1个条目。如何存储和打印结构中的每个条目。

@IBAction func press(_ sender: Any) {
    contacts.append(Person(name: a.text!, surname: b.text!  , phone: Int(c.text!)!))
    print(self.contacts.description)
}

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

1 个答案:

答案 0 :(得分:0)

您可以创建一个人数组,并在有人按下按钮时附加到该数组。以下是swift playground的一个例子。

struct Person {
    var name: String
    var surname: String
    var phone: Int
}
var contacts = [Person]()

func press(name: String, surname: String, phone: Int) {
    contacts.append(Person(name: name, surname: surname, phone: phone))
    print(contacts.description)
}

press(name: "Aks", surname: "Homes", phone: 123)
press(name: "Harry", surname: "Potter", phone: 124)
press(name: "Ron", surname: "Weisly", phone: 345)
press(name: "Shan", surname: "Wate", phone: 456)