Skip to content

Instantly share code, notes, and snippets.

Created July 24, 2021 17:33
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?

I’m trying to decode two slightly different JSON API responses to the same Codable type, Account. Mapping userResponse.json’s uid to id is trivial, but extracting the nested user is stumping me.

Any suggestions would be greatly appreciated!

struct Account: Codable {
typealias ID = String
var id: ID
var uid: String?
var avatar: String?
var name: String
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
if let id = try values.decodeIfPresent(String.self, forKey: .uid) { = id
} else { = try values.decode(String.self, forKey: .id)
self.avatar = try values.decode(String.self, forKey: .avatar) = try values.decode(String.self, forKey: .name)
"id": "team_ba3d8621-3c66-421a-8c46-f1ea6dfa27a1",
"name": "Acme, Inc.",
"avatar": "02d2608a-7526-4821-ad27-3d329b674dc8",
"user": {
"uid": "f5f5e86e-b75e-4cc7-a3be-ddeecbd9c7a6",
"name": "John Appleseed",
"avatar": "9283df3f-54d3-4329-8d6b-dbc90f8a9a38"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment