Created
November 29, 2023 14:12
-
-
Save Bonney/0c4666989e74b5eb875b0ce245c00827 to your computer and use it in GitHub Desktop.
This appears the be the bare-minimum workaround currently needed to use Swift's `Measurement` type in SwiftData.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Model | |
| final public class Drink { | |
| /// Holds the JSON-encoded data blob representing the Measurement. | |
| private var _measurement: Data? | |
| /// The actual Measurement, encoded/decoded on-the-fly. | |
| @Transient var measurement: Measurement<UnitVolume> { | |
| get { getMeasurement() } | |
| set { setMeasurement(newValue) } | |
| } | |
| private func getMeasurement() -> Measurement<UnitVolume> { | |
| _$observationRegistrar.access(self, keyPath: \._measurement) | |
| if let data = self.getValue(forKey: \._measurement) { | |
| do { | |
| return try JSONDecoder().decode(Measurement<UnitVolume>.self, from: data) | |
| } catch { | |
| print(error) | |
| } | |
| } | |
| return Measurement(value: 0.0, unit: UnitVolume.fluidOunces) | |
| } | |
| private func setMeasurement(_ newValue: Measurement<UnitVolume>) { | |
| _$observationRegistrar.withMutation(of: self, keyPath: \._measurement) { | |
| do { | |
| let data = try JSONEncoder().encode(newValue) | |
| self.setValue(forKey: \._measurement, to: data) | |
| } catch { | |
| print(error) | |
| self.setValue(forKey: \._measurement, to: nil) | |
| } | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This seems like a good candidate for a Macro, and not even one that's restricted to this use case.
Now to learn how to write macros...
Basically a macro should be able to transform this:
in to this: