gpt4 book ai didi

swift - 如何在 Swift 中使用 Realm 获取特定 parent 的所有 child +孙子?

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

我有一个 3 个数据库设置,例如父->子->孙,到目前为止,我可以设法获取特定父级的子级,但无法深入到另一个级别。

class Parent : Object {
@objc dynamic var name : String = ""
let childs = List<Child>()
}

class Child : Object {
@objc dynamic var name : String = ""
let grandchilds = List<Grandchild>()
var giveBirth = LinkingObjects(fromType: Parent.self, property: "childs")
}

class Grandchild : Object {
@objc dynamic var name : String = ""
var giveBirth = LinkingObjects(fromType: Child.self, property: "grandchilds")
}

我用这条线来计算 child 的数量:

if let parent = itemsFromParentList?[indexPath.row] {    
cell.detailTextLabel?.text = "\(parent.childs.count)"
}

但我想获得特定 parent 的所有 child +孙子的总数,例如“你有多少 child 和孙子?”。

非常感谢!!!

最佳答案

注意“child”的复数形式是“children”

如果我没理解错的话,你需要平面映射 parent 的孙辈,然后计算它,然后加上 child 的数量。

let childrenPlusGrandchildrenCount = parent.childs.flatMap { $0.grandchilds }.count + parent.childs.count

关于swift - 如何在 Swift 中使用 Realm 获取特定 parent 的所有 child +孙子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56077149/

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