5

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
}
7
  • How would you expect to chance all elements without iterating them all? Btw you should declare all properties as non optional and constants. Only declare a property as optional if they might be nil. Commented Jan 27, 2020 at 6:24
  • @LeoDabus , there are native methods like "filter" and "map" for Array that I can't use properly at the moment. Commented Jan 27, 2020 at 6:26
  • have you tried Map function ? Commented Jan 27, 2020 at 6:26
  • they will loop as well Commented Jan 27, 2020 at 6:26
  • 1
    No idea how to use map. It's saying '$0.' is immutable. Commented Jan 27, 2020 at 6:29

1 Answer 1

22

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}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.