Search code examples
iosswiftpropertiesrealmpersistence

How can I save variables with value type Measurement<UnitType> using Realm Swift?


Does Realm Swift support saving and retrieving data with value type Measurement? Here is the class structure of the data I'm trying to save:

class Race: Object {
@objc dynamic var raceDistance: Measurement<UnitLength>?
@objc dynamic var nettTime = Measurement<UnitDuration>?
}

Solution

  • Measurements themselves are not supported by Realm, but they conform to Codable, so you can save an encoded version of them:

    @objc dynamic var encodedRaceDistance: Data?
    // Realm 10.10+
    // @Persisted var encodedRaceDistance: Data?
    

    And you can add a computed property like this to get the Measurement<UnitLength> from the data:

    var raceDistanceMeasurement: Measurement<UnitLength>? {
        get {
            if let encoded = encodedRaceDistance {
                return try? JSONDecoder().decode(Measurement<UnitLength>.self, from: encoded)
            }
            return nil
        }
        
        set {
            if let newValue = newValue {
                encodedRaceDistance = try? JSONEncoder().encode(newValue)
            } else {
                encodedRaceDistance = nil
            }
        }
    }