Last active
March 15, 2021 14:34
-
-
Save quanganhdo/a7429f034b934093f3590b56b2f4842a to your computer and use it in GitHub Desktop.
JSONDecoder
This file contains hidden or 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 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