Instantly share code, notes, and snippets.

Embed
What would you like to do?
extension Place {
enum CodingKeys: String, CodingKey {
case name = "placeName"
case lat
case lon
case dateAdded
case info
}
static let dateAddedFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "YYYY-mm-dd"
return formatter
}()
static let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(Place.dateAddedFormatter)
return decoder
}()
static let encoder: JSONEncoder = {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(Place.dateAddedFormatter)
return encoder
}()
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
let lat = try container.decode(Decimal.self, forKey: .lat)
let lon = try container.decode(Decimal.self, forKey: .lon)
coordinate = Coordinate(latitude: lat, longitude: lon)
dateAdded = try container.decode(Date.self, forKey: .dateAdded)
info = try container.decodeIfPresent(String.self, forKey: .info)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(coordinate.latitude, forKey: .lat)
try container.encode(coordinate.longitude, forKey: .lon)
try container.encode(name, forKey: .name)
try container.encode(dateAdded, forKey: .dateAdded)
try container.encodeIfPresent(info, forKey: .info)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment