Using enum as property of Realm model

后端 未结 5 489
感动是毒
感动是毒 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: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.

提交回复
热议问题