Created
May 3, 2019 10:28
-
-
Save NduatiK/fe1e6af1c9c5886af92071b49bc79aae to your computer and use it in GitHub Desktop.
Convert JSON date strings to date objects automatically using reflection
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
extension Object { | |
static func setPropertiesToDate(in dict: [String: Any]) -> [String: Any] { | |
var dict = dict | |
for property in dateConvertibles { | |
if let dateStr = dict[property] as? String, | |
let date = dateStr.toISODate()?.date { | |
dict[property] = date | |
} else if (dict[property] as? Date) != nil { | |
continue | |
} else { | |
dict[property] = nil | |
} | |
} | |
return dict | |
} | |
private func getDateConvertibles() -> [String] { | |
var dates = [String]() | |
for case let (label?, value) in Mirror(reflecting: self as Any).children { | |
if value is Date { | |
dates.append(label) | |
} else { | |
let submirror = Mirror(reflecting: value) | |
if submirror.subjectType == (Optional<Date>).self { | |
dates.append(label) | |
} | |
} | |
} | |
return dates | |
} | |
private static var dateConvertibles: [String] { | |
let key = self.className() | |
if let dateConvertibles = dateConvertibleStore[key] { | |
return dateConvertibles | |
} else { | |
let convertibles = self.init().getDateConvertibles() | |
dateConvertibleStore[key] = convertibles | |
return convertibles | |
} | |
} | |
private static var dateConvertibleStore: [String: [String]] = { | |
return [String: [String]]() | |
}() | |
static func stringifyDates(in dict: inout [String: Any]) { | |
for key in dict.keys { | |
if let date = dict[key] as? Date { | |
dict[key] = date.iso8601 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment