Persisting Swift Enumerations With Realm.io
Swift enums are a great way to give semantic meaning to attributes that are not self-explanatory. If used right they provide us with a much more readable codebase and a way to quickly choose a right value without reviewing the documentation.
Which would you prefer?
The latter tells the whole story right away, doesn’t it? However, since it is a custom enum and not an atomic type Realm can not store it right away. But fear not, this can be easily fixed!
How to store enums with Realm
The idea here is to provide custom getters and setters for our enum and store an atomic representation in Realm.
This is our example enumeration which enumerates all task types:
Now, since we can’t store the TaskType object in our Realm storage we have to store some kind of an identifier that we can later translate to an enum representation.
TaskType is conveniently an enumeration of
Ints which means we can just store its
rawValue. If we, however, have an enumeration of a type that Realm does not support (such as
UInt) we may opt to store an index of the enumerated value or assign each with an identifier that we can store.
To store the representation we will create a private variable that will contain the identifier and a public variable (which Realm will not try to persist) with a set of accessors to manipulate with the persisted variable accordingly.
As you can see, we kept the
privateType which is compatible with Realm private to make sure we use the
type variable that supports our enumeration.
The defined getters and setters for the
type variable are in charge of translating the stored identifier to our enumeration and vice-versa.
Originally published at itworkslocal.ly on June 23, 2016.