Created
June 8, 2017 04:58
-
-
Save bcbroom/9ec74b5a774d402e7aaf814f42dd2de8 to your computer and use it in GitHub Desktop.
Using a generic struct to represent a top level object for JSON response for Swift 4's Codable protocol
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 UIKit | |
| let jsonDataEnclosed = """ | |
| { "data" : | |
| { | |
| "name": "Monalisa Octocat", | |
| "email": "support@github.com", | |
| "date": "2011-04-14T16:00:49Z" | |
| } | |
| } | |
| """.data(using: .utf8)! | |
| struct ResponseData<T: Codable>: Codable { | |
| let data: T | |
| } | |
| struct Author : Codable { | |
| let name: String | |
| let email: String | |
| let date: Date | |
| } | |
| let decoder = JSONDecoder() | |
| decoder.dateDecodingStrategy = .iso8601 | |
| let response = try decoder.decode(ResponseData<Author>.self, from: jsonDataEnclosed) | |
| let author = response.data | |
| print(author.name) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment