I have the following struct
struct Vehicle: Codable, Identifiable {
@DocumentID var id: String?
var name: String
}
As long as I use the default Swift decoder I can load Firestore entries without any issue (using document.data(as: ), and id contains the document ID.
However I now need a custom decode function inside that struct, and that's where things go wrong.
I can load all fields without any issue, but the document ID is not filled out.
I tried like this:
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let id = try container.decodeIfPresent(DocumentID<String>.self, forKey: .id) {
self.id = id.wrappedValue
}
But it gives me nil.
I found some other answers but they talk about DocumentReference which is a type that doesn't (or no longer?) exist.
How can I solve this?
Thanks
Decode the Document ID using:
_id = try container.decode(DocumentID<String>.self, forKey: .id)
for the corresponding variable:
@DocumentID var id: String?
This will place the document ID into the ID variable (note the required "_" before id).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With