swift 中带有解码器的 RLMArray:对成员错误的模糊引用

RLMArray in swift with decoder : Ambiguous reference to member error

我想在混合 Objective-C 和 Swift 应用程序中使用 Realm 与 Codable 一起使用,Realm 对象可以导出到 Objective-C ;

class Person2 : RLMObject,Decodable {
      @objc dynamic var  name = ""
      convenience init(_  name:String) {
         self.init()
         self.name = name
      }
 }

class RepairShop2 : RLMObject,Decodable {
   @objc dynamic var name = ""
   @objc dynamic var contact:Person2?
   @objc dynamic var persons = RLMArray<Person2>(objectClassName: Person2.className())

   private enum RepairShop2CodingKeys: String, CodingKey {
       case name
       case contact
       case persons
   }

   convenience init(name: String, contact: Person2,  persons: RLMArray<Person2>) {
        self.init()
        self.name = name
        self.contact = contact
        self.persons = persons
   }

   convenience required init(from decoder: Decoder) throws {
      let container = try decoder.container(keyedBy: RepairShop2CodingKeys.self)
      let name = try container.decode(String.self, forKey: .name)
      let contact = try container.decode(Person2.self, forKey: .contact)
      let personArray = try container.decode(RLMArray<AnyObject>, forKey: .persons)   
 // this line error: Ambiguous reference to member 'decode(_:forKey:)'**

      let persons = RLMArray<Person2>(objectClassName: Person2.className())
      persons.addObjects(personArray)
      self.init(name: name, contact: contact, persons: persons)
  }
}

let personArray = try container.decode(RLMArray<AnyObject>, forKey: .persons)   
 // this line error: Ambiguous reference to member 'decode(_:forKey:)'**

RLMArray.self我也试过了,失败

RLMArray的解码类型怎么写?

RLMRealm 不符合 Decodable,因此您无法立即将其解析为 RLMRealm。而是尝试类似的东西:

let persons = RLMArray<Person2>(objectClassName: Person2.className())
persons.addObjects(try container.decode([Person2].self, forKey: .persons) as NSFastEnumeration)

作为旁注。将不同的领域混合到一个模型中是个坏主意,以后可能会吃亏。