I’ve written a custom ValueTransformer to store an object type that does not receive automatic compliance for SwiftData:
- How to use SwiftData ValueTransformer with a custom NSMeasurement Dimension Unit?
I now want to store collections of that same type as variables on a SwiftData model:
@Model
class TestModel {
// Works after adding custom MeasurementTransformer
@Attribute(.transformable(by: MeasurementTransformer.self)) let measurement: NSMeasurement
// Not working
let measurementArray: [NSMeasurement]
let measurementDict: [String: NSMeasurement]
init(measurement: NSMeasurement, measurementArray: [NSMeasurement], measurementDict: [String : NSMeasurement]) {
self.measurement = measurement
self.measurementArray = measurementArray
self.measurementDict = measurementDict
}
}
This throws errors for the Array and Dictionary:
Referencing instance method ‘setValue(forKey:to:)’ on ‘Array’ requires that ‘NSMeasurement’ conform to ‘PersistentModel’
Referencing instance method ‘getValue(forKey:)’ on ‘Array’ requires that ‘NSMeasurement’ conform to ‘PersistentModel’
Is there any special syntax for @Attribute(.transformable(by:
(or any other way) to share code between the single-object transformer and a transformer for when that type is packed into an array or dictionary? Or do I need to write entirely new ValueTransformers for every situation where that type appears in a collection?