I'm trying to make a deep copy of a list of the following objects:
struct Book {
var title: String
var author: String
var pages: Int
}
struct BookShelf {
var number: Int
}
class BookShelfViewModel {
var bookShelf: BookShelf
var number: Int
var books: [BookViewModel]?
init(bookShelf: BookShelf) {
self.bookShelf = bookShelf
self.number = bookShelf.number
}
required init(original: BookShelfViewModel) {
self.bookShelf = original.bookShelf
self.number = original.number
}
}
class BookViewModel {
var book: Book
var title: String
var author: String
var pages: Int
init(book: Book) {
self.book = book
self.title = book.title
self.author = book.author
self.pages = book.pages
}
required init(original: BookViewModel) {
self.book = original.book
self.title = original.title
self.author = original.author
self.pages = original.pages
}
}
Books for BookShelf is fetched in the BookShelfViewModel.
If I go like:
var copiedArray = originalArray
for bs in copiedArray {
bs.books = bs.books.filter { $0.title == "SampleTitle" }
}
The above filter both the copiedArray and the originalArray, and I obviously just want the copiedArray altered.
When I clone the array like this:
var originalArray = [BookShelfViewModel]()
... // Fill the array
var clonedArray = originalArray.clone()
clonedArray is cloned, but clonedArray.books is empty.
I've created the extension and followed this gist. How do I clone the array in the objects in the array?
I've done a quick playground to visualize the problem, hopefully it helps understand what I'm talking about.

cloneis completely unnecessary. simplylet array2 = array1makes a unique array.BookShelfViewModelandBookViewModel, but then ask whyBookShelfisn't properly copying itsbooks... How about showing us your implementation ofBookShelfinstead of these view model objects?BookorBookshelfdefinitions and you showoriginalArrayas alet, so you can't add objects to it. IsBooka class or a struct? See how to create a minimal reproducible example. Why does yourBookViewModelextract theBookproperties? Why not make those properties computed variables that access the underlyingBook's properties?