It is easy to use Realm with classes by inheriting from Object
. But how would I save a struct
containing several fields to realm in Swift? E.g.
struct DataModel {
var id = 0
var test = "test"
}
I know the documentation is clear about supported types. But maybe there is nice workaround or - even better - someone from realm could write about future plans about structs.
Swift 4 shortest answer
Save structs as Data in Realm
Use the magic
To save a
struct
in Realm, means copying the data into a RealmObject
. The reason why RealmObjects
are classes and notstructs
is because they are not inert values, but auto-updating objects that represent the persisted data in Realm. This has practical benefits, such as the fact that a RealmObject
's data is lazy loaded.You can take advantage of Realm's approach by responding to the change notifications from a Realm instance. For example if your
UITableView
data source is based off an array property on a RealmObject
, as long as you have an instance of that object, you are guaranteed that after the notification it represents the correct values. Used properly this can simplify your code versus having multiple copies of values as structs.You can do what suggests Ludovic, or you can automate that process and get rid of that boilerplate code for each of your structs by using Unrealm.
I' suggest you to use protocols, to achive what you want.
1) Create your Struct
2) Create your Realm Object
3) Use protocols to transform our struct to Realm Object
4) Make your struct persistable
With these tools in place, we are ready to implement the insertion methods of our persistence layer.
5) Exemple to write datas
5) Use the magic!
Amazing source : Using Realm with Value Types & My Article