Attempting to sort a swiftdata query by a pre-set order that is currently in an array.
The array is a list of instruments:
let instruments = [flute, clarinet, saxophone]
Each instance of Student will have the instrument specified:
Student(firstName = "bob", instrument = "clarinet"]
I want to order the query of students in the same order of that array of instruments. (So this example would be sort order #2)
Any suggestions on the best way to approach that? Much appreciated.
I have tried a suggestion found here to use a dictionary with uniqueKeysWithValues to set the order based on it’s integer positon:
let instrumentOptions = ["Flute", "Oboe", "Bassoon", "Clarinet", "Bass Clarinet", "Alto Saxophone", "Tenor Saxophone", "Bari Saxophone", "Trumpet", "Horn", "Trombone", "Baritone", "Tuba", "Percussion"]
let instrumentOrder = Dictionary(
uniqueKeysWithValues: instrumentOptions
.enumerated()
.map { (key: $0.element, value: $0.offset) }
)
this gave the error:
Cannot use instance member ‘instrumentOptions’ within property initializer; property initializers run before ‘self’ is available
Working in Xcode 15.3, and iOS 17.4 if that helps.