Last active
February 3, 2021 06:07
-
-
Save MarioIannotta/08ab96ed4d96fdf9cdf13d4460f62353 to your computer and use it in GitHub Desktop.
A little extension to easily decode date with custom formats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
var json = """ | |
{ | |
"lastSyncDate": "2018-10-28T09:03:59+0000", | |
"posts": [ | |
{ | |
"id": 0, | |
"title": "Swift 4 Codable: tips and tricks", | |
"link": "https://medium.com/@MarioIannotta/swift-4-codable-tips-and-tricks-7ab4674736d2", | |
"publicationDate": "23/09/2018" | |
}, | |
{ | |
"id": 1, | |
"title": "Handle swift logs and testing safely and painless", | |
"link": "https://medium.com/@MarioIannotta/handle-swift-test-and-log-safely-c825d6006bc4", | |
"publicationDate": "22/08/2016" | |
} | |
] | |
} | |
""" | |
extension KeyedDecodingContainer where Key: CodingKey { | |
func decodeDate(from key: Key, format: String) throws -> Date? { | |
let dateAsString = try decode(String.self, forKey: key) | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = format | |
return dateFormatter.date(from: dateAsString) | |
} | |
} | |
struct PostsServiceResponse: Decodable { | |
struct Post: Decodable { | |
enum CodingKeys: String, CodingKey { | |
case id | |
case title | |
case link | |
case publicationDate | |
} | |
let id: Int | |
let title: String | |
let link: String | |
let publicationDate: Date? | |
public init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
id = try container.decode(Int.self, forKey: .id) | |
title = try container.decode(String.self, forKey: .title) | |
link = try container.decode(String.self, forKey: .link) | |
publicationDate = try container.decodeDate(from: .publicationDate, format: "dd/MM/yyyy") | |
} | |
} | |
enum CodingKeys: String, CodingKey { | |
case lastSyncDate | |
case posts | |
} | |
let lastSyncDate: Date? | |
let posts: [Post] | |
public init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
lastSyncDate = try container.decodeDate(from: .lastSyncDate, format: "yyyy-MM-dd'T'HH:mm:ssZ") | |
posts = try container.decode([Post].self, forKey: .posts) | |
} | |
} | |
let data = json.data(using: .utf8) ?? Data() | |
let jsonDecoder = JSONDecoder() | |
let postsServiceResponse = try? jsonDecoder.decode(PostsServiceResponse.self, from: data) | |
print(postsServiceResponse.debugDescription) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment