Created
February 7, 2020 21:03
-
-
Save woolsweater/ebfd7d5edc589a878c6ad6f457d01640 to your computer and use it in GitHub Desktop.
This file contains 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 | |
/** | |
A decodable type that expects its data to be enclosed in a | |
keyed container. | |
For example, using JSON, a `User` object might be delivered | |
inside another object, with `"user"` as the key: | |
``` | |
{ "user" : { "name" : "Alice", "rank" : "Colonel" } } | |
``` | |
*/ | |
protocol EnvelopeDecodable : Decodable { | |
/** The key for this type in the enclosing container. */ | |
static var contentsKey: String { get } | |
} | |
/** | |
Decodable representation for another decodable type | |
that is delivered as a nested object in a keyed container. | |
*/ | |
struct Envelope<T : EnvelopeDecodable> : Decodable { | |
/** The wrapped value that we actually want to extract. */ | |
let contents: T | |
private enum CodingKeys : CodingKey { | |
case contents | |
var stringValue: String { T.contentsKey } | |
} | |
} | |
// Example: | |
struct User : EnvelopeDecodable { | |
static let contentsKey = "user" | |
let name: String | |
let rank: String | |
let favoriteCereal: String | |
} | |
let json = """ | |
{ | |
"user" : { | |
"name" : "Alice", | |
"rank" : "Colonel", | |
"favoriteCereal" : "Corn flakes" | |
} | |
} | |
""".data(using: .utf8)! | |
let response = try! JSONDecoder().decode(Envelope<User>.self, from: json) | |
print(response.contents) // User(name: "Alice", rank: "Colonel", favoriteCereal: "Corn flakes") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
JSON responses sometimes come with this wrapper level around the object that we actually care about, which can be annoying to deal with in the
Codable
world. A common technique to handle it is to make aDecodable
helper type that represents that wrapper, so we can still take advantage of synthesized implementations. Here we just extend that idea a bit by making the top-level key a property of the inner object type. Then the one typeEnvelope
, orWrapper
, or whatever name you choose, can handle any content type.