ios – Default worth for Codable property that doesn’t exists with PropertyWrapper


i created a propertyWrapper like this:

@propertyWrapper
public struct DefaultTodayDate: Codable {
    public var wrappedValue: Date

    personal let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "y-MM-dd'T'HH:mm:ss"

        return formatter
    }()

    public init(from decoder: Decoder) throws {
        let container = attempt decoder.singleValueContainer()
        var stringDate = ""
        do {
            stringDate = attempt container.decode(String.self)
            self.wrappedValue = self.dateFormatter.date(from: stringDate) ?? Date()
        } catch {
            self.wrappedValue = Date()
        }
    }

    public func encode(to encoder: Encoder) throws {
        attempt wrappedValue.encode(to: encoder)
    }
}

and a mannequin like this:

struct MyModel: Codable {
    @DefaultTodayDate var date: Date
}

so, if i need to parse this json file, all the pieces is okay:

let json = #"{ "date": "2022-10-10T09:09:09" }"#.information(utilizing: .utf8)!
let consequence = attempt! JSONDecoder().decode(MyModel.self, from: json)

print(consequence) // consequence.date is: 2022-10-10 09:09:09 +0000
-----

let json = #"{ "date": "" }"#.information(utilizing: .utf8)!
let consequence = attempt! JSONDecoder().decode(MyModel.self, from: json)

print(consequence) // consequence.date is: Date()
-----

let json = #"{ "date": null }"#.information(utilizing: .utf8)!
let consequence = attempt! JSONDecoder().decode(MyModel.self, from: json)

print(consequence) // consequence.date is: Date()

however i need to additionally parse a json with out date property.however i get. deadly error:

let json = #"{ "guide": "check" }"#.information(utilizing: .utf8)!
let consequence = attempt! JSONDecoder().decode(MyModel.self, from: json)

// Deadly error: 'attempt!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "date", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No worth related to key CodingKeys(stringValue: "date", intValue: nil) ("date").", underlyingError: nil))

print(consequence) // i need to consequence.date be Date() 

Leave a Reply