Using enum as property of Realm model

后端 未结 5 487
感动是毒
感动是毒 2020-12-07 16:34

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          


        
相关标签:
5条回答
  • 2020-12-07 16:54

    Example with RealmEnum and RealmOptional

    @objc enum MyEnum: Int, RealmEnum {
        case first
        case second
    }
    
    final class MyEntry: Object {
        //It should be let
        let someVariable = RealmOptional<CRUD>()
    }
    
    //using
    myEntry.someVariable.value = MyEnum.first
    
    0 讨论(0)
  • 2020-12-07 16:58

    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.

    0 讨论(0)
  • 2020-12-07 17:00

    Diogo T's solution worked before recent updates of RealmSwift. Eventually we now have to conform to RealmEnum protocol to be able to be a managed property of Realm Object.

    @objc enum MyEnum: Int, RealmEnum {
        ...
    }
    

    Or add below in some place:

    extension MyEnum: RealmEnum { }
    

    RealmSwift documentation for it

    0 讨论(0)
  • 2020-12-07 17:01

    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

    0 讨论(0)
  • 2020-12-07 17:08

    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
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题