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?
}