具有包含数组的元素的数组的深层副本?

时间:2018-10-14 01:03:03

标签: swift xcode deep-copy

我正在尝试制作以下对象列表的深层副本:

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
    }
}

在BookShelfViewModel中获取BookShelf的图书。

如果我喜欢:

var copiedArray = originalArray

for bs in copiedArray {
   bs.books = bs.books.filter { $0.title == "SampleTitle" }
}

上面的过滤器同时对copyedArray和originalArray进行过滤,显然,我只想更改copyedArray。

当我像这样克隆数组时:

var originalArray = [BookShelfViewModel]()
... // Fill the array
var clonedArray = originalArray.clone()

clonedArray被克隆,但是clonedArray.books为空。

我已经创建了扩展名,并遵循了this的要旨。如何在数组中的对象中克隆数组?

我已经做了一个快速的操场来可视化问题,希望它有助于理解我在说什么。

enter image description here

1 个答案:

答案 0 :(得分:1)

BookShelfViewModel的复制初始化器中,您实际上并没有克隆books数组。您需要将self.books = original.books?.clone()添加到required init(original: BookShelfViewModel)

class BookShelfViewModel: Copying {
    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.books = original.books?.clone()
        self.number = original.number
    }
}