You just need to iterate your array indices using forEach method and use the array index to update its element property:
struct ViewHolder {
let name: String
let age: Int
var isMarried: Bool
}
var viewHolders: [ViewHolder] = [.init(name: "Steve Jobs", age: 56, isMarried: true),
.init(name: "Tim Cook", age: 59, isMarried: true)]
viewHolders.indices.forEach {
viewHolders[$0].isMarried = false
}
viewHolders // [{name "Steve Jobs", age 56, isMarried false}, {name "Tim Cook", age 59, isMarried false}]
You can also extend MutableCollection and create a mutating method to map a specific property of your collection elements as follow:
extension MutableCollection {
mutating func mapProperty<T>(_ keyPath: WritableKeyPath<Element, T>, _ value: T) {
indices.forEach { self[$0][keyPath: keyPath] = value }
}
}
Usage:
viewHolders.mapProperty(\.isMarried, false)
viewHolders // [{name "Steve Jobs", age 56, isMarried false}, {name "Tim Cook", age 59, isMarried false}]
Mapfunction ?