Zin Win Htet
Zin Win Htet

Reputation: 2565

How to update a specific property value of all elements in array using Swift

Let's say I already have an Array of ViewHolder which is viewHolderList: [ViewHolder]. I want all isMarried field of elements to "false" in a single line without looping.

struct ViewHolder {
    var name: String?
    var age: Int?
    var isMarried: Bool = true
}

Upvotes: 5

Views: 7038

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236295

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}]

Upvotes: 22

Related Questions