我正在通过CloudKit使用核心数据,我想要做的是将数据从那里导出到文件中.任何项都可以具有子项,这意味着子项可以具有子项,这意味着项可以是任意数量的嵌套级别.我的问题是,我不知道如何获取嵌套项的路径,以便将其子项添加到itemEntry数组中.我的另一个问题是,即使我确实有一个名为pathToItem的变量,具有正确的路径,如[0][0][0],我也不知道如何使用该变量来更新itemEntry数组,因为我假设itemEntries[pathToItem]不起作用.
@State private var itemEntries: [ItemEntry] = []
struct ItemEntry: Codable {
var title: String
var children: [ItemEntry]
}
private func populateNestedData(items: [Item], itemsAreNested: Bool = false) {
for item in items {
if (!itemsAreNested) {
itemEntries.append(createItemEntry(item: item))
}
else {
//Here is my problem. The item could be any number of levels nested. How can I get the path to the item so that I can use it to append the child item to the itemEntries array?
let pathToItem = ?????
//And even if I did have pathToItem such as [0][0][0] how would I then use that correctly here?
itemEntries[pathToItem].children.append(createItemEntry(item: item))
}
if (!item.childrenArray.isEmpty) {
var children = coreDataController.getChildrenOfItemForExporting(item: item)
populateNestedData(items: children, itemsAreNested: true)
}
}
}
private func createItemEntry(item: Item) -> ItemEntry {
return ItemEntry(
title: item.title ?? "",
children: []
)
}