Sorting with Complex & Arbitrary Nested Models

I’m developing an app for inspections that allows users to develop their own template for inspections. Because of this, my data structure has become more than a little complex (see below).

This structure does allow a great deal in flexibility, through, as users can add groups, rows, and individual fields as needed. For example, users can add a header group, then a row to the header with fields for the Building Number, Unit Number, & Inspection Date.

However, I don’t have an efficient way to sort the inspections by the values in these fields. SwiftData sorting is keypath based, which won’t allow me to sort the inspections based on the values only in fields with specific labels.

As an alternative, I can query for fields with a specific label and do a compactMap to the inspection. But this doesn’t scale well when working with potentially hundreds or thousands of inspections as compactMap takes a lot longer then the query takes. It also doesn’t work well if I want to filter inspections or sort using values in multiple user defined fields.

Models below are greatly simplified to just get the point across. More than happy to provide some additional code if asked when I’m back at my laptop with the source code. (Typing this on my iPad at the moment)

@Model final class Inspection {
  // init and other fields

  var groups: [Group]?
}

@Model final class Group {
  // init and other fields

  @Relationship(inverse: \Inspection.groups)
  var inspection: Inspection?
  var rows: [Row]?
}

@Model final class Row {
  // init and other fields

  @Relationship(inverse: \Group.rows)
  var group: Group?
  var fields: [Field]?
}

@Model final class Field {
  // init and other fields
  var label: String?
  var type: FieldType // enum, denoting what type of data this is storing
  var stringValue: String?
  var boolValue: Bool?
  var dateValue: Date?
  @Attribute(.externalStorage) var dataValue: Data?

  @Relationship(inverse: \Row.fields)
  var row: Row?
}

You have a complex and dynamic design which will make the whole solution more complex. When you write "...sort the inspections based on the values only in fields with specific labels" it not only is an example of the complexity but it is quite frankly hard to understand how/if it should work. An inspection can have many groups and a group can have many rows so even if you are only sorting on one label with a specific field it will be a complex task to sort the rows and groups for a single inspection not to mention comparing inspections.

Since I have no idea what an inspection is in this context and neither what your fields will be filled with it's hard to give any kind of advice but for starters, do you really, really need to sort the inspectors in this manner?

Sorting with Complex & Arbitrary Nested Models
 
 
Q