based on Chris Mitchelmore answer
Details
- Xcode Version 10.3 (10G8), Swift 5
Solution
import Foundation
extension Decodable {
init(from value: Any,
options: JSONSerialization.WritingOptions = [],
decoder: JSONDecoder) throws {
let data = try JSONSerialization.data(withJSONObject: value, options: options)
self = try decoder.decode(Self.self, from: data)
}
init(from value: Any,
options: JSONSerialization.WritingOptions = [],
decoderSetupClosure: ((JSONDecoder) -> Void)? = nil) throws {
let decoder = JSONDecoder()
decoderSetupClosure?(decoder)
try self.init(from: value, options: options, decoder: decoder)
}
init?(discardingAnErrorFrom value: Any,
printError: Bool = false,
options: JSONSerialization.WritingOptions = [],
decoderSetupClosure: ((JSONDecoder) -> Void)? = nil) {
do {
try self.init(from: value, options: options, decoderSetupClosure: decoderSetupClosure)
} catch {
if printError { print("\(Self.self) decoding ERROR:\n\(error)") }
return nil
}
}
}
Usage
struct Item: Decodable {
let id: Int
let name: String
let isActive: Bool
var date: Date
}
let dictionary = ["id": 1, "name": "Item", "is_active": false,
"date": "2019-08-06T06:55:00.000-04:00"] as [String : Any]
do {
let item1 = try Item(from: dictionary) { decoder in
decoder.keyDecodingStrategy = .convertFromSnakeCase
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
decoder.dateDecodingStrategy = .formatted(dateFormatter)
}
print(item1)
} catch {
print("Error: \(error)")
}
print("\n========================")
let item2 = Item(discardingAnErrorFrom: dictionary)
print(String(describing: item2))
print("\n========================")
let item3 = Item(discardingAnErrorFrom: dictionary, printError: true)
print(String(describing: item3))
print("\n========================")
let item4 = Item(discardingAnErrorFrom: dictionary){ decoder in
decoder.keyDecodingStrategy = .convertFromSnakeCase
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
decoder.dateDecodingStrategy = .formatted(dateFormatter)
}
print(String(describing: item4))
Usage log
Item(id: 1, name: "Item", isActive: false, date: 2019-08-06 10:55:00 +0000)
========================
nil
========================
Item decoding ERROR:
keyNotFound(CodingKeys(stringValue: "isActive", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"isActive\", intValue: nil) (\"isActive\").", underlyingError: nil))
nil
========================
Optional(__lldb_expr_5.Item(id: 1, name: "Item", isActive: false, date: 2019-08-06 10:55:00 +0000))