比方说,我已经有一个数组的ViewHolder是viewHolderList: [ViewHolder]。我希望isMarried对象的所有字段在一行中都为“ false ”而不循环。那可能吗?
ViewHolder
viewHolderList: [ViewHolder]
isMarried
struct ViewHolder{ var name: String? var age: Int? var isMarried: Bool = true }
您只需要indices使用forEach方法迭代数组并使用数组索引来更新其element属性:
indices
forEach
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}]