Swift 模型未从 Firestore 读取数据

Swift model not reading data from Firestore

我有一个名为 Requirements 的基本模型和另一个名为 AccountRequirements 的更具体的模型。

当我尝试阅读 currentDeadline 属性 时,如果我使用 Requirements 它工作正常。如果我使用 AccountRequirements,它会显示为 nil

我不明白为什么。我猜它与 class 有某种关系。我总是在我的模型中使用 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)
}

如果你想将它解码为 subclass,那么你需要将 class 而不是 superclass 提供给 document.data(as:)。您还需要为 subclass 实现 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)
}

Requirements Some text
AccountRequirements Some text 42