Klemen
Klemen

Reputation: 2182

How to use custom initializer on an Realm object inside a class with generic type?

I have a class called ObjectManager which has generic type O: Object, Persistable. This way I can have one class that can operate with multiple different subclasses of realm Object. But the problem is in the last line cache = O(message: "hello world") the error is: Incorrect argument label in call (have 'message:', expected 'value:')

When typing it suggests me that I can use initializer of Persistable protocol, but complain during the compiling, that it expect an initializer from Object class. Is it possible to cast Persistable initializer?

protocol Persistable {
  init(message: String)
}

class CustomObject: Object, Persistable {
  dynamic var message: String = ""
  required convenience init(message: String) {
    self.init()
    self.message = message
  }
}

class ObjectManager<O>: NSObject where O: Object, O: Persistable {
  var cache: O?

  func didReceive(message: String) {
    cache = O(message: "hello world")
  }
}

Upvotes: 1

Views: 1359

Answers (1)

AustinZ
AustinZ

Reputation: 1787

If you make your CustomObject class final, and replace your initializer with a factory method, you will get code which does what you want. Unfortunately, the Swift compiler error messages are so cryptic in this case as to be completely unhelpful.

protocol Persistable {
    static func factory(message: String) -> Self
}

final class CustomObject: Object, Persistable {
    dynamic var message: String = ""
    static func factory(message: String) -> CustomObject {
        let x = CustomObject()
        x.message = message
        return x
    }
}

class ObjectManager<O>: NSObject where O: Object, O: Persistable {
    var cache: O?

    func didReceive(message: String) {
        cache = O.factory(message: "hello world")
    }
}

Upvotes: 4

Related Questions