如何使用Realm Swift保存值类型为Measurement <unittype>的变量?

时间:2018-11-21 05:42:18

标签: ios swift properties realm persistence

Realm Swift是否支持保存和检索值类型为Measurement的数据?这是我要保存的数据的类结构:

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

1 个答案:

答案 0 :(得分:1)

Measurements themselves are not supported by Realm, but you can store their constituent parts.

A Measurement is just a value with a unit. So for raceDistance, you could store

let raceDistance = RealmOptional<Double>()
@objc dynamic var raceDistanceUnit: String? = nil

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

var raceDistanceMeasurement: Measurement<UnitLength>? {
    get {
        if let distance = raceDistance.value, let unit = raceDistanceUnit {
            return Measurement(value: distance, unit: UnitLength(symbol: unit))
        }
        return nil
    }

    set {
        raceDistance.value = newValue?.value
        raceDistanceUnit = newValue?.unit.symbol
    }
}