1

Realm doesn't support DateInterval to be store into the database. For now our team do the following:

private let _intervalBegins = List<Date>()
private let _intervalEnds = List<Date>()

var dateIntervals: [DateInterval] {
    get {
        var intervals = [DateInterval]()
        for (i, startDate) in _intervalBegins.enumerated() {
            let endDate = _intervalEnds[i]
            intervals.append(DateInterval(start: startDate, end: endDate))
        }
        return intervals
    }

    set {
        _intervalBegins.removeAll()
        _intervalBegins.append(objectsIn: newValue.compactMap{ $0.start })
        _intervalEnds.removeAll()
        _intervalEnds.append(objectsIn: newValue.compactMap{ $0.end })
    }
}

Is there a more "proper" way to do this? Maybe to store both the start and end dates into one property/database column? And get those value directly without "parsing" them with another variable as we do now.

Thanks!

pacification
  • 5,838
  • 4
  • 29
  • 51
SquareBox
  • 823
  • 1
  • 10
  • 22

1 Answers1

0

As you notice, Realm doesn't support DateInterval, but Realm is able to save your custom objects. In this case you can create your own RealmDateInterval (or so) and create initializer, that allows you to create object from DateInterval:

dynamic var start: Date = Date()
dynamic var end: Date = Date()

convenience init(dateInterval: DateInterval) {
    self.init()
    self.start = dateInterval.start
    self.end = dateInterval.end
}

Next thing, when you retrieve RealmDateInterval from Realm you really want DateInterval instead. Here you can create a bridge function, that can convert RealmDateInterval to DateInterval or create a protocol with convert func and adopt it to RealmDateInterval (i.e. clearly show everybody RealmDateInterval has specific functionality).

protocol DateIntervalConvertible {
    func toDateInterval() -> DateInterval
}

extension RealmDateInterval: DateIntervalConvertible {

    func toDateInterval() -> DateInterval {
        return DateInterval(start: start, end: end)
    }

}
pacification
  • 5,838
  • 4
  • 29
  • 51