What about using a property wrapper?
Usage:
@FirestoreDate private(set) var createdAt: Date
@FirestoreDate private(set) var updatedAt: Date
FirestoreDate Property Wrapper:
import Foundation
import FirebaseFirestore
@propertyWrapper
struct FirestoreDate: Codable {
var wrappedValue: Date
init(wrappedValue: Date) {
self.wrappedValue = wrappedValue
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let timestamp = try? container.decode(Timestamp.self) {
wrappedValue = timestamp.dateValue()
} else if let date = try? container.decode(Date.self) {
wrappedValue = date
} else {
wrappedValue = Date()
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(Timestamp(date: wrappedValue))
}
}