Zaid Pathan Zaid Pathan - 1 year ago 41
Swift Question

Swift updating child array updates parent array as well

Here is my code.

I have one model, which consist array of another model.

class MyModel{
var arrSubModel = [SubModel]()

class SubModel{
var value1 = String()
var value2 = String()

Now in my class I have 2 variables for holding array of MyModel.

class MyVC:UIViewController {
var arrMyModel = [MyModel1,MyModel2,MyModel3]
var arrFilterModel = []

func filter() {
arrFilterModel = []

for model in arrMyModel {
for subModel in model.arrSubModel {
if conditionMet {
} else {
//remove that subModel

but when I access
is removed from it but it should be only removed from

I think I'm doing something wrong.
Hope you guys can help.

Thank you.

Answer Source

This question would be much simpler to answer if you expressed your intent more clearly

  • Your code is incredibly hard to read because of the crazy indentation
  • Your code is incredibly hard to understand because of its over-generalization
  • Your code isn't following Swift's doctrine of immutability and pure functions.

From what I can gather, you want arrFilterModel to be set to a subset of arrMyModel depending on some condition, without effecting the original arrMyModel.

There's a much simpler way of doing what you're trying to do:

func giveMeABetterName() { //don't call it "filter", it's meaningless.
   let copy = arrMyModel
   let arrFilterModel ={$0.arrSubMode}.filter{$0 == foo} //substitute in the condition

I would recommend you change this to not abuse object state, and to use params/returns instead:

func giveMeABetterName(source: [MyModel]) -> [SubModel] {
    return{$0.arrSubMode}.filter{$0 == foo} //substitute in the condition

You're also suffering from the unintentional data sharing that comes from the reference semantics of classes. Switching to the value semantics of structs will fix this.