Dave Long Dave Long - 5 months ago 17
iOS Question

Using enum as property of Realm model

Is it possible to use an Enum as a property for my model? I currently have a class like this:

class Checkin: RLMObject {
dynamic var id: Int = 0
dynamic var kind: String = "checked_in"
var kindEnum: Kind = .CheckedIn {
willSet { self.kind = newValue.rawValue }
}

enum Kind: String {
case CheckedIn = "checked_in"
case EnRoute = "en_route"
case DroppedOff = "dropped_off"
}
....
}


It works okay, but I'd like to be able to have the
kind
property be the Enum and have Realm automatically call
.rawValue
on the property when it is saving an object to the store. Is this possible in Realm or is there a feature request already out there for it?

Answer

You should override your kindEnum's setter and getter for this case:

enum Kind: String {
  case CheckedIn
  case EnRoute
  case DroppedOff
}

class Checkin: Object {
  dynamic var id = 0
  dynamic var kind = Kind.CheckedIn.rawValue
  var kindEnum: Kind {
    get {
      return Kind(rawValue: kind)!
    }
    set {
      kind = newValue.rawValue
    }
  }
}