在 Swift 4.0 中,我有一个结构数组。有没有办法使用 keyPaths 来更新数组中的所有项目,而无需像 map 或 forEach 那样手动迭代?类似于 objc 的东西[people makeObjectsPerformSelector: @selector(setName:) withObject: @"updated"];
struct Person {
var name: String? = "Empty"
}
var people = [Person(), Person()]
//This only updates one person:
people[keyPath: \[Person].[0].name] = "single update"
//I'm looking to accomplish something like this without a map
let updatedPeople = people.map { (person: Person) -> Person in
var copy = person
copy[keyPath: \Person.name] = "updated"
return copy
}
像 people[keyPath: \[People].all.name] = "全部更新而不手动迭代"