Passing array through segue in swift

后端 未结 3 1216
南笙
南笙 2021-01-24 08:20

I\'ve been struggling for a few days now with passing an array from my SecondViewController to my FirstViewController using Swift.

From my rese

3条回答
  •  醉酒成梦
    2021-01-24 08:57

    Did you know that array in Swift are value type. So, when you assign array to some other variable or pass it to some method, the value is passed; not the reference to actual object. When you pass your array to second view controller, it copies the content of your original array. You are then adding to this array which do not change the content of original array.

    I would suggest you to create some kind of callback or delegate pattern from second view controller to first view controller to inform the changes such that first view controller would also modify the original array content.

    Here is a small portion of code that will help you understand this,

    let originalArray = ["a", "b", "c"]
    
    var newArray = originalArray
    
    newArray.append("d")
    
    print(originalArray) // prints ["a", "b", "c"]
    print(newArray) // prints ["a", "b", "c", "d"]
    

提交回复
热议问题