0

In code below, list1 is original Array. when i copy list1 in list2, it passes "allCardList" array as reference but i want to create copy of list1 so when i change in list2 it shouldn't change original Array (list1)

class Card {
    var availableBalance        = "5"
}
class DataCacheManager: NSObject {
    var allCardList             = [Card]()
}
var card = Card()
card.availableBalance = "10"

var list1 = DataCacheManager()
list1.allCardList.append(card)

var list2 = DataCacheManager()

for item in list1.allCardList {
    list2.allCardList.append(item)
}

list2.allCardList[0].availableBalance = "20"

print(list1.allCardList[0].availableBalance) // print 20 but should return 10

Any help you that?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Ali Murad
  • 9
  • 1
  • 4

3 Answers3

2

A class has reference semantics. The simplest solution is to use value semantics

struct Card ...
vadian
  • 274,689
  • 30
  • 353
  • 361
0

Take a look at this question, it describes the process of copying a single object.

Implementing copy() in Swift

After you added the ability of copying, iterate through your array with a for loop to create a copied array from your existing data.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
0

Please read these references How do I make a exact duplicate copy of an array?1 and deep copy array In you case there other ways to achive your requirement without copying the whole array. For a example you could have an readonly original value as a object in Card and have another variable for the new value and so on.

Gihan
  • 2,476
  • 2
  • 27
  • 33