Using enum as a property of the Realm model

Can I use Enum as a property for my model? I currently have a class:

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 fine, but I would like to have the kind property of being Enum and have Realm automatically call .rawValue on the property when it saves the object in storage. Is this possible in Realm or is there any function request there?

+42
enums ios realm
Mar 18 '15 at 13:21
source share
3 answers

You must override the kindEnum and getter installer 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 } } } 
+67
Mar 19 '15 at 15:55
source share

I clarified this model a bit.

 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 } } } 

It allows us to write

 myClassInstance.thing = .Thing1 

(storing "Thing1" in privateThing) but prevents input

 myClassInstance.privateThing = "Thing4" 

which is not a valid value, thus preserving data integrity.

+26
Nov 02 '15 at 15:11
source share

Since Realm supports Objective-C enums and they are represented 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 / from String , you can use a custom initializer for Kind and toString .

This is stated on GitHub

This works with Swift 3.0 and Realm 2.0.2

+7
Dec 26 '16 at 10:32
source share



All Articles