Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DhavalDobariya86/822c3c746c7f7f26075d12180f0f1bd5 to your computer and use it in GitHub Desktop.
Save DhavalDobariya86/822c3c746c7f7f26075d12180f0f1bd5 to your computer and use it in GitHub Desktop.
Codable with Date decoding strategy
import UIKit
struct Country: Codable {
let name: String
let capital: String
let independanceDay: Date
}
let jsonData: Data = """
{
"name": "United States of America",
"capital": "Washington, D.C.",
"independanceDay": "1776-07-04"
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
// To convert from date in `String` format of JSON to Swift `Date`
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
decoder.dateDecodingStrategy = .formatted(dateFormatter)
let country = try! decoder.decode(Country.self, from: jsonData)
print("Country Independance Day = \(dateFormatter.string(from: country.independanceDay))")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment