2

There is a few old thread that discuss the usage of Enums in Realm, and I adopted one them which works fine but I want to make sure that that is still the recommended way of doing it.

Is the following code the current-recommended way to use Enums with Realm?

Realm Object

enum SeatPreference: String {
    case Window
    case Middle
    case Aisle
}

class Ticket:Object{
    @objc private dynamic var preference = SeatPreference.Window.rawValue

    var seatPreference: SeatPreference {
        get { return SeatPreference(rawValue: preference)! }
        set { preference = newValue.rawValue }
    }
}

Usage:

ticket.seatPreference = .Middle

Again, everything works fine, I just want someone to confirm that there is still not a better way of doing it.

fs_tigre
  • 10,650
  • 13
  • 73
  • 146
  • 1
    Do you care how enum value is stored inside of `Realm` "table"? If you don't, you may just use `Int` based `enums` directly without proxy type conversion. – user28434'mstep Apr 24 '19 at 12:21
  • @user28434 No, not really. Would you mind showing me an example of what you are talking about? Also, do you see any benefit by storing them as `Int`s. – fs_tigre Apr 24 '19 at 13:13
  • 2
    Just change `: String` to `: Int` add `@objc` to the type, mark `seatPreference` with `dynamic` and remove `getter`/`setter`. It is done. And benefit is native support, and an `Int` consumes less space that a `String`. – user28434'mstep Apr 24 '19 at 13:20
  • Possible duplicate of [Using enum as property of Realm model](https://stackoverflow.com/questions/29123245/using-enum-as-property-of-realm-model) – user28434'mstep Apr 24 '19 at 13:20
  • I will give it a try. Thanks. – fs_tigre Apr 24 '19 at 13:50

0 Answers0