Moving through child list of list

I have the following structure:

struct SoundModel:Codable
{
    var sort : String? = ""
    var type : String? = ""
    var name : String? = ""
    var pic_file_path : String? = ""
    var text : String? = ""
    var related_item : [SoundModel]? = nil
}
var soundModel :SoundModel = SoundModel()
var dataSourceSounds :[SoundModel] = [SoundModel()]
 self.dataSourceSounds = soundModel.related_item!

the above soundModel can be represented as tree where there is a root with a children of related_item, what I force when I implement this structure in an iOS app with using a tableview, I couldn't figure out how can I traverse (showing) related_item of it's child and how to get back to the parent from child,

when first click of an item in my table view I get

dataSourceSounds = dataSourceSounds[indexPath.row].related_item

and in second click get

 dataSourceSounds =  dataSourceSounds[indexPath.row].related_item

where I'll get second level of related_item
And so on,
How can I implement such idea to make it capable to click a button to go back a level?

Thanks in advance

There is no "best" answer here. What is best for you will depend on a lot of other factors in your app, and your own coding style.

One approach is to use a class for SoundModel instead of a struct. Remember that there can be many copies of a value of a struct type, so the concept of "parent" and "child" gets a bit murky there.

With classes, the values are unique, so parent/child relationships are easier to grasp.

If you change struct to class, you can add a weak link from the child back to the parent (weak to avoid annoying retain cycles):

class SoundModel:Codable
{
    weak var parent: SoundModel?
    …
}

The only problem is that you would need to set the reference from the child to the parent separately from the JSON decoding, and would have to exclude the parent property from the JSON encoding. So you'd need a customization of Codable.

There are other approaches, too. You could keep a struct SoundModel, but embed it in an instance of a TreeNode class of some kind. Or you could stay completely with structs, and use some kind of "tree locator index" to navigate the tree of structs, which would allow you move up as well as down.

Terms of Service

Privacy Policy

Cookie Policy