小编典典

如何更新数组中所有对象的特定值?迅速

swift

比方说,我已经有一个数组的ViewHolderviewHolderList: [ViewHolder]。我希望isMarried对象的所有字段在一行中都为“ false ”而不循环。那可能吗?

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

阅读 227

收藏
2020-07-07

共1个答案

小编典典

您只需要indices使用forEach方法迭代数组并使用数组索引来更新其element属性:

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