Reputation: 19
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?
Upvotes: 1
Views: 3128
Reputation: 2536
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.
Upvotes: 0
Reputation: 58029
Take a look at this question, it describes the process of copying a single object.
After you added the ability of copying, iterate through your array with a for
loop to create a copied array from your existing data.
Upvotes: 0
Reputation: 285069
A class
has reference semantics. The simplest solution is to use value semantics
struct Card ...
Upvotes: 2