I’m trying to create an OutlineGroup in SwiftUI to display an hierarchal folder like structure:
class Folder : Object, ObjectKeyIdentifiable {
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var name: String
@Persisted var parent: Folder?
@Persisted var icon = "folder"
@Persisted(originProperty: "parent") var children: LinkingObjects<Folder>
@Persisted(originProperty: "folder") var items: LinkingObjects<Item>
}
I have an @ObservedResults property in my view:
@ObservedResults(Folder.self, filter: NSPredicate(format: "parent == nil")) var rootFolders
And in my view:
var body: some View {
NavigationView {
OutlineGroup(rootFolders[0], children: \.children) { folder in
Text("\(folder.name)")
}
Text("Content")
}
}
This code though doesn’t compile, I’m getting the error “Key path value type ‘LinkingObjects’ cannot be converted to contextual type ‘LinkingObjects?’”
for the \.children keypath.
I’m kind of at a loss as to how to resolve this to get the OutlineGroup to get the item’s children.
I’m not quite sure even how to “unwrap” the children property into an [Folder]?.
Would the forward link be a List and the inverse be a LinkingObjects?
class Folder : Object, ObjectKeyIdentifiable {
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var name: String
@Persisted var parent: Folder?
@Persisted var icon = "folder"
@Persisted var childList = List<Folder>() //forward link to the child folders
@Persisted(originProperty: "childList" var linkedParent: LinkingObjects<Folder> //back link to parent
}
That being said, since the child folder can only ever have a single parent, what about forgoing the LinkingObjects and just use a single parent property?
class Folder : Object, ObjectKeyIdentifiable {
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var name: String
@Persisted var parent: Folder?
@Persisted var icon = "folder"
@Persisted var childList = List<Folder>() //forward link to the child folders
@Persisted var parentFolder: Folder!
}
It’s a bit more work but that keeps the relationships one-to-many and then the reverse is one-to-one.