更新数组中的对象

ara*_*ker 0 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)
Run Code Online (Sandbox Code Playgroud)

如何将国王的年龄从 3 更新到 4?

ara*_*ker 9

好的,这对我有用。

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