【发布时间】:2018-07-23 07:21:23
【问题描述】:
在 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] = "无需手动迭代即可全部更新"
【问题讨论】:
-
people.indices.forEach { idx in people[idx][keyPath: \Person.name] = "updated" } -
据我所知,与关键路径无关。
标签: arrays swift struct updating keypaths