DEV Community

Khoa Pham
Khoa Pham

Posted on

Composition in Realm

Original post https://github.com/onmyway133/blog/issues/13

There is time we have models that have some kind of inheritance, like Dog, Cat, Mouse can be Animal. We can use composition to imitate inheritance, we just need to make sure it has unique primary key

Cat and Dog

These are pretty much basic Realm objects

class Dog: Object {
  dynamic var id: Int = 0

  required convenience init(json: [String: Any]) {
    self.init()
    id <- json.integer(key: "id")
  }
}

class Cat: Object {
  dynamic var id: Int = 0

  required convenience init(json: [String: Any]) {
    self.init()
    id <- json.integer(key: "id")
  }
}
Enter fullscreen mode Exit fullscreen mode

Animal

Here Animal can contain either dog or cat, we can add more if there are many other "inheritance" of Animal. The required init makes sure Animal can only be init with 1 type of child class

class Animal: Object {
  dynamic var id: Int = 0

  dynamic var cat: Cat?
  dynamic var dog: Dog?

  required convenience init(cat: Cat) {
    self.init()
    self.cat = cat
    self.id = cat.id
  }

  required convenience init(dog: Dog) {
    self.init()
    self.dog = dog
    self.id = dog.id
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)