Skip to content

Instantly share code, notes, and snippets.

@quanganhdo
Last active March 15, 2021 14:34
Show Gist options
  • Select an option

  • Save quanganhdo/a7429f034b934093f3590b56b2f4842a to your computer and use it in GitHub Desktop.

Select an option

Save quanganhdo/a7429f034b934093f3590b56b2f4842a to your computer and use it in GitHub Desktop.
JSONDecoder
import Foundation
struct Response: Decodable {
var time: Date
}
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let json = """
{"time":"2021-03-14T02:28:53Z"}
""".data(using: .utf8)!
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
// Fatal error: 'try!' expression unexpectedly raised an error:
// Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "time", intValue: nil)]
// , debugDescription: "Date string does not match format expected by formatter.", underlyingError: nil)):
// file __lldb_expr_1/Test.playground, line 17
let response = try! decoder.decode(Response.self, from: json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment