Using enum as property of Realm model

耗尽温柔 提交于 2019-11-27 09:39:40

问题


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?


回答1:


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

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

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



回答2:


I've refined this model a little further.

enum Thing: String {
    case Thing1
    case Thing2
    case Thing3
}

then in my Realm class object:

class myClass : Object {
    private dynamic var privateThing = Thing.Thing1.rawValue
    var thing: Thing {
        get { return Thing(rawValue: privateThing)! }
        set { privateThing = newValue.rawValue }
    }
}

This allows us to write

myClassInstance.thing = .Thing1

(storing "Thing1" into privateThing), but prevents typing of

myClassInstance.privateThing = "Thing4"

which is not a valid value so preserving data integrity.




回答3:


Since Realm support Objective-C enums and they are representable by Int you can use this:

class Checkin: Object {
  dynamic var id: Int = 0
  dynamic var kind: Kind = .checkedIn

  @objc enum Kind: Int {
    case checkedIn
    case enRoute
    case droppedOff
  }
  ....
}

If you need to parse to/from String you can use a custom initializer for Kind and an toString function.

There is a discussion about this in GitHub

This works with Swift 3.0 and Realm 2.0.2



来源:https://stackoverflow.com/questions/29123245/using-enum-as-property-of-realm-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!