Search code examples
swiftrangerealm

Represent range value in RealmSwift?


I need to create something like this:

import RealmSwift

class UserObject: Object {
  @Persisted var ageRange: ClosedRange<Int>
}

But I get error Generic struct 'Persisted' requires that 'ClosedRange<Int>' conform to '_Persistable'

How to map ClosedRange<Int> to a single object which is supported by realm (without of splitting ClosedRange<Int> into 2 Int)?

P.S. note: there are may be similar questions but they are all about the older RealmSwift version which doesn't involve @Persisted


Solution

  • Other than a little bit of code duplication, I really don't see what "looks strange" about splitting the range into 2 Ints.

    If you want to avoid code duplication when there are multiple such pairs of properties, you can write an RealmIntRange Realm object that is persistable.

    class RealmIntRange: Object {
        @Persisted var min: Int = 0
        @Persisted var max: Int = 0
    }
    

    Then in UserObject,

    @Persisted var ageRange: RealmIntRange?
    

    Unfortunately this has to be an optional type.