Created
August 21, 2017 13:57
-
-
Save stinger/7140232de1e0a4ea1f72b39b2052beb3 to your computer and use it in GitHub Desktop.
Swift 4: Codable dates
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 | |
struct LocationData: Codable { | |
var city: String | |
var country: String | |
var address: String? | |
} | |
struct Item: Codable { | |
var name: String | |
var createdAt: Date | |
var locationData: LocationData? | |
enum CodingKeys: String, CodingKey { | |
case name = "title" | |
case createdAt = "created_at" | |
case locationData | |
} | |
} | |
let item = Item( | |
name: "A test item", | |
createdAt: Date(), | |
locationData: LocationData(city: "London", country: "UK", address: nil) | |
) | |
let formatter = DateFormatter() | |
formatter.dateFormat = "EEEE, MMM d, yyyy" | |
let encoder = JSONEncoder() | |
encoder.dateEncodingStrategy = .formatted(formatter) | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .formatted(formatter) | |
if let data = try? encoder.encode(item), let json = String(data: data, encoding: .utf8) { | |
print("Encoded JSON:\n\t\(json)") | |
if let ship = try? decoder.decode(Item.self, from: data) { | |
print("\nDecoded class:\n\t\(ship)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment