79273838

Date: 2024-12-12 04:42:21
Score: 0.5
Natty:
Report link

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))
    }
}
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): What
  • Low reputation (0.5):
Posted by: Samuel Folledo