我创建了一个属性包装器,如下所示:
@propertyWrapper
public struct DefaultTodayDate: Codable {
public var wrappedValue: Date
private 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 = try decoder.singleValueContainer()
var stringDate = ""
do {
stringDate = try container.decode(String.self)
self.wrappedValue = self.dateFormatter.date(from: stringDate) ?? Date()
} catch {
self.wrappedValue = Date()
}
}
public func encode(to encoder: Encoder) throws {
try wrappedValue.encode(to: encoder)
}
}
还有一个这样的模型:
struct MyModel: Codable {
@DefaultTodayDate var date: Date
}
因此,如果我想要解析这个json文件,一切都很正常:
let json = #"{ "date": "2022-10-10T09:09:09" }"#.data(using: .utf8)!
let result = try! JSONDecoder().decode(MyModel.self, from: json)
print(result) // result.date is: 2022-10-10 09:09:09 +0000
-----
let json = #"{ "date": "" }"#.data(using: .utf8)!
let result = try! JSONDecoder().decode(MyModel.self, from: json)
print(result) // result.date is: Date()
-----
let json = #"{ "date": null }"#.data(using: .utf8)!
let result = try! JSONDecoder().decode(MyModel.self, from: json)
print(result) // result.date is: Date()
但是我也想解析一个没有date
个属性的JSON.致命错误:
let json = #"{ "book": "test" }"#.data(using: .utf8)!
let result = try! JSONDecoder().decode(MyModel.self, from: json)
// Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "date", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"date\", intValue: nil) (\"date\").", underlyingError: nil))
print(result) // i want to result.date be Date()