How can I store a Dictionary with RealmSwift?

gabuchan picture gabuchan · Nov 19, 2015 · Viewed 16.5k times · Source

Considering the following model:

class Person: Object {
    dynamic var name = ""
    let hobbies = Dictionary<String, String>()
}

I'm trying to stock in Realm an object of type [String:String] that I got from an Alamofire request but can't since hobbies has to to be defined through let according to RealmSwift Documentation since it is a List<T>/Dictionary<T,U> kind of type.

let hobbiesToStore: [String:String]
// populate hobbiestoStore
let person = Person()
person.hobbies = hobbiesToStore

I also tried to redefine init() but always ended up with a fatal error or else.

How can I simply copy or initialize a Dictionary in RealSwift? Am I missing something trivial here?

Answer

marius picture marius · Nov 19, 2015

Dictionary is not supported as property type in Realm. You'd need to introduce a new class, whose objects describe each a key-value-pair and to-many relationship to that as seen below:

class Person: Object {
    dynamic var name = ""
    let hobbies = List<Hobby>()
}

class Hobby: Object {
    dynamic var name = ""
    dynamic var descriptionText = ""
}

For deserialization, you'd need to map your dictionary structure in your JSON to Hobby objects and assign the key and value to the appropriate property.