更新数组中的对象

时间:2018-03-10 22:41:54

标签: swift

我有以下代码:

    struct Person {
    var name: String
    var age: Int
    var check: Bool
}

var anotherPerson: Person
var people: [Person] = []

anotherPerson = Person(name: "Jan", age: 55, check: true)
people.append(anotherPerson)
anotherPerson = Person(name: "Diesel", age: 9, check: false)
people.append(anotherPerson)
anotherPerson = Person(name: "King", age: 3, check: false)
people.append(anotherPerson)

如何将King的年龄从3更新为4?

1 个答案:

答案 0 :(得分:2)

好的,这适合我。

if let index = people.index(where: {$0.name == "King"}) {
    people[index].age = 4
}