Skip to content

Instantly share code, notes, and snippets.

@bcbroom
Created June 8, 2017 04:58
Show Gist options
  • Select an option

  • Save bcbroom/9ec74b5a774d402e7aaf814f42dd2de8 to your computer and use it in GitHub Desktop.

Select an option

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
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