gpt4 book ai didi

swift - 具有包含数组的元素的数组的深拷贝?

转载 作者:行者123 更新时间:2023-11-28 14:08:16 27 4
gpt4 key购买 nike

我正在尝试对以下对象的列表进行深度复制:

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

BookShelf 的书籍在 BookShelfViewModel 中获取。

如果我这样走:

var copiedArray = originalArray

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

上面的过滤器同时过滤了 copiedArray 和 originalArray,显然我只想改变 copiedArray。

当我像这样克隆数组时:

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

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

我已经创建了扩展并关注了 this要旨。如何克隆数组中对象中的数组?

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

enter image description here

最佳答案

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

关于swift - 具有包含数组的元素的数组的深拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52798623/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com