Ios Swift模型未从Firestore读取数据

Ios Swift模型未从Firestore读取数据,ios,swift,xcode,swift5,Ios,Swift,Xcode,Swift5,我有一个叫做Requirements的基本模型和另一个叫做AccountRequirements的更具体的模型 当我尝试读取currentdimdate属性时,如果我使用Requirements它工作正常。如果我使用AccountRequirements,结果是nil 我不明白为什么。我猜这与类有关。我总是在我的模型中使用struct,但是由于我不能从struct继承,所以我在这里使用class class Requirements: Codable { var commonProper

我有一个叫做
Requirements
的基本模型和另一个叫做
AccountRequirements
的更具体的模型

当我尝试读取
currentdimdate
属性时,如果我使用
Requirements
它工作正常。如果我使用
AccountRequirements
,结果是
nil

我不明白为什么。我猜这与
有关。我总是在我的模型中使用
struct
,但是由于我不能从
struct
继承,所以我在这里使用
class

class Requirements: Codable {
    var commonProperty: String

    // works
    var currentDeadline: Int?
    
    enum CodingKeys: String, CodingKey {
        case commonProperty = "common_property"

        case currentDeadline = "current_deadline"
    }
}

class AccountRequirements: Requirements {
    // doesnt work 
    var currentDeadline: Int?
    
    enum CodingKeys: String, CodingKey {
        case currentDeadline = "current_deadline"
    }
}
我对数据进行如下解码:

documentReference.addSnapshotListener { [self] documentSnapshot, error in
    guard let document = documentSnapshot else {
        self.error = error!.localizedDescription
        return
    }
    
    self.user = try? document.data(as: Requirements.self)
}

如果要将其解码为子类,则需要将该类而不是超类赋予
document.data(as:)
。您还需要实现
init(from:)
子类才能正确解码它

required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    currentDeadline = try container.decodeIfPresent(Int.self, forKey: .currentDeadline)
    try super.init(from: decoder)
}
下面是一个带有硬编码json值的示例

let data = """
    { "common_property": "Some text",
      "current_deadline": 42
    }
    """.data(using: .utf8)!


do {
    let result = try JSONDecoder().decode(Requirements.self, from: data)
    print(type(of: result), result.commonProperty)
    let result2 = try JSONDecoder().decode(AccountRequirements.self, from: data)
    print(type(of: result2), result2.commonProperty, result2.currentDeadline ?? "")
} catch {
    print(error)
}
一些文本的要求
一些课文42


为什么子类中的属性与超类中的属性完全相同?你是如何解码数据的?它只在其中一个里面,只是为了演示,我把它放在两个上面。我更新了我关于如何解码数据的问题。太好了!,这对我也有用。。所以我需要为我想要的每个属性手动执行此操作,对吗?有没有其他更简单的方法可以做到这一点,也许是通过结构?我的想法是,我需要有一个基础模型和一个具有一些额外属性的子模型。最简单的解决方案可能是使用struct而不是class,并将旧超类的属性复制到所有struct中。你会得到一些重复的属性,但是你要实现的自定义代码会少得多,甚至可能一个都没有。。。好吧,我把所有的事情都放在一起,那些不常见的人是可选的,所以即使他们不在那里,也没关系。